我很难理解为什么以下代码编译:
public class MethodRefs {
public static void main(String[] args) {
Function<MethodRefs, String> f;
f = MethodRefs::getValueStatic;
f = MethodRefs::getValue;
}
public static String getValueStatic(MethodRefs smt) {
return smt.getValue();
}
public String getValue() {
return "4";
}
}
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么第一个赋值是有效的 - getValueStatic
显然匹配指定的Function
类型(它接受一个MethodRefs
对象并返回一个String
),但第二个让我感到困惑 - 该getValue
方法不接受任何参数,那么为什么它仍然有效分配给它f
?
Pet*_*rey 50
第二个
f = MethodRefs::getValue;
Run Code Online (Sandbox Code Playgroud)
是相同的
f = (MethodRefs m) -> m.getValue();
Run Code Online (Sandbox Code Playgroud)
对于非静态方法,始终存在隐式参数,该参数this
在被调用者中表示.
注意:字节代码级别的实现略有不同,但它的功能相同.
非静态方法基本上将其this
引用作为一种特殊的参数.通常,该参数是以特殊方式编写的(在方法名称之前,而不是在其后的括号内),但概念是相同的.该getValue
方法接受一个MethodRefs
对象(它this
)并返回一个字符串,因此它与Function<MethodRefs, String>
接口兼容.
让我们充实一点:
import java.util.function.Function;
public class MethodRefs {
public static void main(String[] args) {
Function<MethodRefs, String> f;
final MethodRefs ref = new MethodRefs();
f = MethodRefs::getValueStatic;
f.apply(ref);
//is equivalent to
MethodRefs.getValueStatic(ref);
f = MethodRefs::getValue;
f.apply(ref);
//is now equivalent to
ref.getValue();
}
public static String getValueStatic(MethodRefs smt) {
return smt.getValue();
}
public String getValue() {
return "4";
}
}
Run Code Online (Sandbox Code Playgroud)
在Java Tutorial中,解释了有4种不同类型的方法引用:
你的情况是#3,这意味着当你有一个MethodRef
ie 的实例时ref
,调用apply
你的函数f
将相当于String s = ref.getValue()
.
归档时间: |
|
查看次数: |
2461 次 |
最近记录: |