java - Java 8 中使用的功能接口(interface)是什么?

标签 java lambda java-8 functional-interface

我在 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 注释对于代码的编译时间检查很有用。除了 staticdefault 和在 @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/

相关文章:

java - 使用java套接字从客户端向服务器发送文本文件

mysql - MySQL查询之Lambda表达式查询

python - 简化代码-根据运算符执行数学运算

java - 流: cannot convert from Stream<Object>的流

Java 8 流 : average and count at once

java - 找不到处理 Intent {act=android.settings.action.MANAGE_WRITE_SETTINGS

java - 如何读取 rsa 公钥形式字符串(由 java 生成,我想用 Python 读取它)

java - JOptionPane 中的可点击链接

java - 如何从 Java 8 中的迭代器获取 n 个第一个值?

java - CDT 词法分析器 : Get Tokens for comments