/**
- 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.
- FunctionalInterface 是一个标记接口。
- Conceptually, a functional interface has exactly one abstract
- method. Since {@linkplain java.lang.reflect.Method#isDefault()
- default methods} have an implementation, they are not abstract.
在概念上一个funcitonalInterface 只有一个抽象方法。可以通过反射的Method#isDefault() 检测。
If an interface declares an abstract method overriding one of the - public methods of {@code 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 {@code java.lang.Object} or elsewhere.
- 如果接口继承并是实现了Object的方法,那么不会作为抽象方法的统计范围。
-
Note that instances of functional interfaces can be created with
- lambda expressions, method references, or constructor references.
- functionalInterface 一般用作lambda表达式,方法引用,构造方法引用
-
If a type is annotated with this annotation type, compilers are
- required to generate an error message unless:
- 被标记了functionalInterface的接口,会在编译的时候做检测
-
- 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 {@code FunctionalInterface}
- annotation is present on the interface declaration.
- 然而,编译器会将只有一个抽象方法的接口,自动认为时functional interface
- @jls 4.3.2. The Class Object
- @jls 9.8 Functional Interfaces
- @jls 9.4.3 Interface Method Body
- @since 1.8
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {} 总结一下:
functional interface 是一个非必须的编译时期的标记接口。
实现方式:
通过统计除default 实现, static 实现, object基础方法以外的抽象方法数量。 如果统计结果直有一个抽象方法,那么编译通过。 否则编译出错。也就是说该功能,在编译期间就生效的注解。