什么是函数式接口 @FunctionalInterface
源码定义
/**
* An informative annotation type used to indicate that an interface
* type declaration is intended to be a <i>functional interface</i> as
* defined by the Java Language Specification.
*
* 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. If
* an interface declares an abstract method overriding one of the
* public methods of {@code java.lang.Object}, that also does
* <em>not</em> 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.
*
* <p>Note that instances of functional interfaces can be created with
* lambda expressions, method references, or constructor references.
*
* <p>If a type is annotated with this annotation type, compilers are
* required to generate an error message unless:
*
* <ul>
* <li> The type is an interface type and not an annotation type, enum, or class.
* <li> The annotated type satisfies the requirements of a functional interface.
* </ul>
*
* <p>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.
*
* @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 {}
翻译
- 如果一个接口只有一个抽象方法,那么该接口就是函数式接口。
- 如果一个接口里面有一个抽象方法,该方法重写了Object的方法,那么不会向接口的抽象方法加1,该接口的抽象方法还是一个,仍然满足函数式接口的定义,那么该接口也会定义为函数式接口。
- 如果我们在某个接口上声明了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该接口,不满足就会报错。
- 如果某一个接口只有一个抽象方法,但是我们并没有在该接口上声明FunctionalInterface注解,那么编译器依旧会将该接口看作函数式接口。
示例
正确定义
- 一般定义
package com.demo.fuctionalface;
@FunctionalInterface
public interface InterfaceDemo {
void say();
}
- 不添加@FunctionalInterface注解编译器也会将此接口当成函数式接口,建议添加
package com.demo.fuctionalface;
public interface InterfaceDemo {
void say();
}
- 重写了Object中的方法,仍然是函数式接口
package com.demo.fuctionalface;
public interface InterfaceDemo {
void say();
@Override
String toString();
}
重点解释一下为什么第三种也是函数式接口:
- 首先 Object类是所有java的父类,所以InterfaceDemo的实现类,直接或者间接的继承Object类,也就是说也继承了Object的toString方法,实现在Object内。只需要实现say()方法即可。子类只需要实现一个抽象方法,符合函数式接口的定义。
错误定义
- 编译器就会报错
package com.demo.fuctionalface;
@FunctionalInterface
public interface InterfaceDemo {
void say();
String MyString();
}