我的密码在这里。我的困惑是在Test.java的主要方法中,第一个案例使用它的实现打印结果,而另一个作为普通的lambda表达式输出它的实际情况。我还想知道他们是否有相同的方法签名导致了问题。
public class Test {
public static void main(String[] args) {
Function<ApplyService, Class<? extends ApplyService>> f1 = ApplyService::run;
System.out.println(f1.apply(new ApplyService1()));
// class Function.ApplyService1 - It's strange, got a result with 'ApplyService1.run'
//
Function<ApplyService, Class<? extends ApplyService>> f2 = Abc::run2;
System.out.println(f2.apply(new ApplyService1())); // null as wish
}
}
interface Abc {
static Class<? extends ApplyService> run2(ApplyService app) {
return null;
}
}
interface ApplyService {
default Class<? extends ApplyService> run() {
return null;
}
}
class ApplyService1 implements ApplyService{
public Class< ? extends ApplyService> run(){
return this.getClass();
}
}发布于 2021-03-26 13:31:07
第一个函数Function<ApplyService, Class<? extends ApplyService>> f1 = ApplyService::run;相当于:
Function<ApplyService, Class<? extends ApplyService>> f1 = apService -> apService.run();因此,在传递类型为ApplyService1的对象时,将调用ApplyService1中实现的方法。
但是第二个函数Function<ApplyService, Class<? extends ApplyService>> f2 = Abc::run2;相当于:
Function<ApplyService, Class<? extends ApplyService>> f2 = apService -> Abc.run2(apService);因为Abc::run2是静态方法引用,所以输入ApplyService对象被传递给run2方法。
发布于 2021-03-26 13:32:31
ApplyService::run是这里描述的“对特定类型的任意对象的实例方法的引用”。注意run是一个实例方法,所以您需要一个实例来调用它。您没有在方法引用中指定任何ApplyService实例(您刚才说的是ApplyService::run),因此,当您调用方法引用时,传递给apply的第一个参数被用作调用实例方法的实例。
在本例中,new ApplyService1()是您调用run的实例,因此当您这样做时:
f1.apply(new ApplyService1())你实际上是在打电话:
new ApplyService1().run()注意参数是如何成为调用方法的实例的。
在Abc::run2的情况下,它是“对静态方法的引用”,因此没有一个“参数成为调用该方法的实例”发生,而且它的工作方式与您预期的一样。
https://stackoverflow.com/questions/66817692
复制相似问题