Java 8中使用了哪些功能接口? [英] What are functional interfaces used for in Java 8?

查看:107
本文介绍了Java 8中使用了哪些功能接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Java 8中的一个新术语:功能接口".在使用 lambda表达式时,我只能找到它的一种用法.

I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions.

Java 8提供了一些内置的功能接口,如果要定义任何功能接口,则可以使用@FunctionalInterface批注.它将允许我们在接口中仅声明一个方法.

Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the @FunctionalInterface annotation. It will allow us to declare only a single method in the interface.

例如:

@FunctionalInterface
interface MathOperation {
    int operation(int a, int b);
}

除了仅使用 lambda表达式以外,它在Java 8中还有什么用?

How useful it is in Java 8 other than just working with lambda expressions?

(问题此处与我问的不同.我问的是为什么在使用lambda表达式时为什么需要函数接口.我的问题是:为什么函数接口除了lambda表达式之外还有其他用途?)

(The question here is different from the one I asked. It is asking why we need functional interfaces while working with lambda expressions. My question is: why other uses do functional interfaces have besides with lambda expressions?)

推荐答案

@FunctionalInterface批注对于检查代码的编译时间很有用.除了staticdefault和用于覆盖@FunctionalInterface中的Object中的方法或用作功能接口的任何其他接口的抽象方法之外,您不能使用多个方法.

@FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your @FunctionalInterface or any other interface used as a functional interface.

但是您可以使用没有此注释的lambda,也可以覆盖没有@Override注释的方法.

But you can use lambdas without this annotation as well as you can override methods without @Override annotation.

来自文档

功能接口只有一种抽象方法.由于默认 方法有一个实现,它们不是抽象的.如果一个接口 声明一个抽象方法,该方法重写以下方法的公共方法之一 java.lang.Object,它也不计入接口的 抽象方法的数量,因为该接口的任何实现都会 可以从java.lang.Object或其他地方实现

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表达式中不能使用此 :

This cannot be used in lambda expression:

public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

但这会导致编译错误:

@FunctionalInterface
public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

无效的"@FunctionalInterface"注释; Foo不是功能 界面

Invalid '@FunctionalInterface' annotation; Foo is not a functional interface

这篇关于Java 8中使用了哪些功能接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆