【问题标题】:Invoking default methods from lambdas从 lambda 调用默认方法
【发布时间】:2015-08-18 18:46:07
【问题描述】:

有没有办法在定义 lambda 时调用默认方法?

例如

@FunctionalInterface
public interface StringCombiner {
    String combine(String s1, String s2);

   default String bar(String s1, String s2) {
        return combine(s1,s2);
   };

}

我想做这样的事情:

StringCombiner sc = (s1, s2) -> /** I want to call bar() here **/

【问题讨论】:

    标签: java lambda java-8


    【解决方案1】:

    这将导致 StackOverflowError :bar 调用 combine,它调用 bar,它调用 combine...

    您需要在其定义中递归引用sc(您不能在lambda 中使用this 来引用由lambda 创建的对象)。我相信这只有在实例或类变量中才有可能。所以它可能看起来像:

    @FunctionalInterface
    public interface StringCombiner {
        String combine(String s1, String s2);
        default String bar(String s1, String s2) { return "bar"; }
    }
    
    //Note: you need the static block to avoid a "self-reference" compilation error
    static StringCombiner sc;
    static {
      sc = (s1, s2) -> sc.bar(s1, s2) + s1 + s2;
    }
    
    public static void main(String[] args) {
        System.out.println(sc.combine("a", "b"));
    }
    

    打印barab

    【讨论】:

    • 哦,抱歉,我忘了从 bar 中删除 combine 的调用。然而,这在这里无关紧要。无论如何,你已经回答了我的问题。谢谢! :)
    • 由于“初始化程序中的自引用”而不起作用
    • @mysh 确实感谢 - 它是使用我第一次发布答案时使用的 Java 8 的早期版本编译的。使用最新版本,您需要拆分声明和初始化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2019-07-18
    • 2018-06-13
    • 2016-08-06
    • 2018-09-14
    • 2016-04-04
    • 2011-10-01
    相关资源
    最近更新 更多