- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在学习 Java 8 中的 Lambda 表达式和方法引用,发现我们可以通过使用“super”来引用方法的父类(super class)版本,如:
super ::名称
但是当我这样做时,它不起作用。这是示例代码:
interface MyInterface {
int someFunc(int x);
}
class A {
static int Func(int y) {
// return (int) (Math.random() * y);
return y;
}
}
class B extends A {
static int Func(int y) {
// return (int) (Math.random() * y);
return y + 1;
}
}
public class Test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
java.util.Scanner scanner = new java.util.Scanner(System.in);
int result = funcOp(B::Func, scanner.nextInt()); // <-This works.
//int result = funcOp(B.super::Func, scanner.nextInt()); <--This is not working.
//Getting: error: not an enclosing class: B
int result = funcOp(B.super::Func, scanner.nextInt());
^
scanner.close();
System.out.println(result);
}
static int funcOp(MyInterface mI, int num) {
return mI.someFunc(num);
}
}
请告诉我,我执行此代码是否有误?据我了解,我们可以传递一个方法“X”作为引用,因为方法“X”满足方法“Y”的条件和行为,并且可能会替换方法在那种情况下是"is"。
这不对吗,我是不是以错误的方式获取了方法引用?
感谢您对此的意见:)
最佳答案
来自 the JLS :
The form super.Identifier refers to the field named Identifier of the current object, but with the current object viewed as an instance of the superclass of the current class.
[...]
The forms using the keyword super are valid only in an instance method, instance initializer, or constructor of a class, or in the initializer of an instance variable of a class. If they appear anywhere else, a compile-time error occurs.
您正在从类类型调用 super
,因此出现编译错误。
正如许多人在评论中建议的那样,您应该在 funcOp
方法中传递 A::Func
。
请注意,您也无法从 Func
方法调用 super
,因为它是一个 static
方法,所以它不是绑定(bind)到类实例。
根据 OP 的评论进行编辑
您可以在实例方法中使用 super
关键字(因此,如果您删除 static),它看起来像这样:
class B extends A {
int Func(int y) {
// e.g:
if (y > 10) {
return super.Func(y); // call Func from the parent class
}
return y + 1;
}
}
关于java - 如何在 lamda 表达式中使用 super::methodName 引用方法的父类(super class)版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53063993/
我是一名优秀的程序员,十分优秀!