在本系列的上一篇文章中,我们讨论了什么是lambda表达式以及如何编写lambda表达式。 在本文中,我们将讨论如何执行lambda表达式。 正如我所说,在上一篇文章的末尾,我们可以使用Java 8的新功能来执行lambda表达式,功能界面。
So what is Functional Interface?
包含单个抽象方法(SAM)的接口称为功能接口。 我们可能知道的一些功能接口是:
接口方法可运行跑()可召回呼叫()可比相比于()动作监听器actionPerformed()
在1.8版中,Java引入了一个注释@FunctionalInterface将接口明确指定为功能接口。 但是注释是可选的。 但是,建议编写注释。 它有助于防止任何其他抽象方法。 如果带有批注的接口包含多个抽象方法,那么我们将得到一个编译时错误,提示:
error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
CustomInterface is not a functional interface
multiple non-overriding abstract methods found in interface CustomInterface
注意:功能接口可以具有多个默认和静态方法。
范例1:
@FunctionalInterface
interface A {
void m1();
}
@FunctionalInterface
interface B extends A {
}
@FunctionalInterface
interface C extends A {
void m1();
}
@FunctionalInterface
interface D extends A {
void m2();
}
在上面的示例中,接口D定义无效,因为它包含两个方法:m1()[从接口A扩展]和m2()。
在下一部分中,我将介绍如何将lambda表达式与功能接口一起使用。