通过lambda表达式实现具有两个抽象方法的接口

时间:2016-03-26 09:03:48

标签: java lambda java-8 functional-interface

在Java 8中,引入了 lambda表达式 来帮助减少样板代码。如果界面只有一个方法,它可以正常工作。如果它由多个方法组成,那么这些方法都不起作用。我该如何处理多种方法?

我们可以选择以下示例

public interface I1()
{
    void show1();
    void show2();
}

然后主要功能的结构是什么来定义主要的方法呢?

4 个答案:

答案 0 :(得分:33)

Lambda表达式仅可用于Eran所说的功能接口,但如果您确实需要接口中的多个方法,则可以将修饰符更改为defaultstatic并在类中覆盖它们必要时实施它们。

public class Test {
    public static void main(String[] args) {
        I1 i1 = () -> System.out.println(); // NOT LEGAL
        I2 i2 = () -> System.out.println(); // TOTALLY LEGAL
        I3 i3 = () -> System.out.println(); // TOTALLY LEGAL
    }
}

interface I1 {
    void show1();
    void show2();
}

interface I2 {
    void show1();
    default void show2() {}
}

interface I3 {
    void show1();
    static void show2 () {}
}

继承

你不应该忘记继承的方法。

此处,I2继承show1show2,因此无法成为功能界面。

public class Test {
    public static void main(String[] args) {
        I1 i1 = () -> System.out.println(); // NOT LEGAL BUT WE SAW IT EARLIER
        I2 i2 = () -> System.out.println(); // NOT LEGAL
    }
}

interface I1 {
    void show1();
    void show2();
}

interface I2 extends I1 {
    void show3();
}

注释

要确保您的界面是功能界面,您可以添加以下注释@FunctionalInterface

@FunctionalInterface <------- COMPILATION ERROR : Invalid '@FunctionalInterface' annotation; I1 is not a functional interface
interface I1 {
    void show1();
    void show2();
}

@FunctionalInterface
interface I2 {
    void show3();
}

答案 1 :(得分:11)

Lambda表达式只能用于实现功能接口,这些接口是具有单个抽象方法的接口。具有两个抽象方法的接口无法通过lambda表达式实现。

答案 2 :(得分:9)

我通常直接在界面中创建一个静态工厂方法:

public inteface I1 {
    void show1();
    void show2();

    public static I1 of(Runnable show1, Runnable show2) {
        return new I1() {
            void show1() { show1.run(); }
            void show2() { show2.run(); }
        };
    }
}

用法:

I1 i1 = I1.of(() -> System.out.println("show1"), () -> System.out.println("show2"));

答案 3 :(得分:4)

您可以随时使用合成:

public inteface I1 {
    void show1();
    void show2();
}

public class I1Adapter {
    private final Runnable r1,r2;
    public I1Adapter(Runnable r1, Runnable r2) {this.r1=r1; this.r2=r2;}
    public void show1() {r1.run();}
    public void show2() {r2.run();}
    public static I1Adapter compose(Runnable r1, Runnable r2) {
        return new I1Adapter(r1,r2);
    }
}

你能做到(使用静态导入):

I1 i1 = compose(()->foo(), ()->bar());