我在 Java 8 中遇到了一个新术语:“函数式接口(interface)”。在使用 lambda 表达式时,我只能找到它的一种用途。
Java 8 提供了一些内置的函数式接口(interface),如果我们想定义任何函数式接口(interface),我们可以使用 @FunctionalInterface
注释。它将允许我们在接口(interface)中只声明一个方法。
例如:
@FunctionalInterface
interface MathOperation {
int operation(int a, int b);
}
除了使用 lambda 表达式之外,它在 Java 8 中还有多大用处?
(问题 here 与我问的不同。它问的是为什么我们在使用 lambda 表达式时需要函数式接口(interface)。我的问题是:除了使用 lambda 表达式之外,函数式接口(interface)的其他用途是什么?)
最佳答案
@FunctionalInterface
注释对于代码的编译时间检查很有用。除了 static
、default
和在 @FunctionalInterface
中覆盖 Object
中的方法的抽象方法之外,您不能有多个方法> 或任何其他用作功能接口(interface)的接口(interface)。
但是你可以使用没有这个注解的 lambda,也可以覆盖没有 @Override
注解的方法。
来自文档
a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere
这个可以在 lambda 表达式中使用:
public interface Foo {
public void doSomething();
}
这个不能在 lambda 表达式中使用:
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
但这会产生编译错误:
@FunctionalInterface
public interface Foo {
public void doSomething();
public void doSomethingElse();
}
Invalid '@FunctionalInterface' annotation; Foo is not a functional interface
关于java - Java 8 中使用的功能接口(interface)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36881826/