首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有实现的Java8函数应用方法

带有实现的Java8函数应用方法
EN

Stack Overflow用户
提问于 2021-03-26 13:17:46
回答 2查看 133关注 0票数 2

我的密码在这里。我的困惑是在Test.java的主要方法中,第一个案例使用它的实现打印结果,而另一个作为普通的lambda表达式输出它的实际情况。我还想知道他们是否有相同的方法签名导致了问题。

代码语言:javascript
复制
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();
    }
}
EN

回答 2

Stack Overflow用户

发布于 2021-03-26 13:31:07

第一个函数Function<ApplyService, Class<? extends ApplyService>> f1 = ApplyService::run;相当于:

代码语言:javascript
复制
Function<ApplyService, Class<? extends ApplyService>> f1 = apService -> apService.run();

因此,在传递类型为ApplyService1的对象时,将调用ApplyService1中实现的方法。

但是第二个函数Function<ApplyService, Class<? extends ApplyService>> f2 = Abc::run2;相当于:

代码语言:javascript
复制
Function<ApplyService, Class<? extends ApplyService>> f2 = apService -> Abc.run2(apService);

因为Abc::run2是静态方法引用,所以输入ApplyService对象被传递给run2方法。

票数 1
EN

Stack Overflow用户

发布于 2021-03-26 13:32:31

ApplyService::run这里描述的“对特定类型的任意对象的实例方法的引用”。注意run是一个实例方法,所以您需要一个实例来调用它。您没有在方法引用中指定任何ApplyService实例(您刚才说的是ApplyService::run),因此,当您调用方法引用时,传递给apply的第一个参数被用作调用实例方法的实例。

在本例中,new ApplyService1()是您调用run的实例,因此当您这样做时:

代码语言:javascript
复制
f1.apply(new ApplyService1())

你实际上是在打电话:

代码语言:javascript
复制
new ApplyService1().run()

注意参数是如何成为调用方法的实例的。

Abc::run2的情况下,它是“对静态方法的引用”,因此没有一个“参数成为调用该方法的实例”发生,而且它的工作方式与您预期的一样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66817692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档