您的位置:首页 > 其它

函数接口

2016-05-15 19:23 411 查看

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
修饰。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: