函数接口

public @interface FunctionalInterface

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification. Conceptually, 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.

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

If a type is annotated with this annotation type, compilers are required to generate an error message unless:

  • The type is an interface type and not an annotation type, enum, or class.
  • The annotated type satisfies the requirements of a functional interface.

However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.


FunctionInterface是一个标记型注解(informative annotation type),根据Java语言规范(JLS Java Language Specification)的定义,这个注解用来指明该接口的类型为函数接口(functional interface),从概念上来讲的话:一个函数接口只能含有一个抽象方法,如果含有一个被default修饰的方法,这个接口不算是含有一个抽象接口,因为default方法已经在接口中被实现了。如果java.lang.Object类中的某些方法被一个接口重写成抽象方法,那么这些抽象方法也不能计为该接口的抽象方法的数目中。因为任何一个实现了该接口的类,即使不实现这些方法,在这些类的父类java.lang.Object中也已经有了实现。

函数接口的实例可以使用:lambda表达式,方法引用或者构造器引用创建。

如果一个类型使用了这个函数接口的注解,如果你不想让编译器报错的话,你就得乖乖的遵循下面的规定:

  • 这个类型一定是接口类型,不能是注解接口(@interface),枚举类型(enum)或者类类型(class)
  • 被这个注解修饰的类型必须满足上面提到的定义(只能含有一个“名正言顺”的抽象方法)

事实上,任意的一个接口如果满足了上述的规定,编译器都会把它当做函数接口,不管这个接口前面有没有使用@FunctionalInterface修饰。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值