JDK8 新特性 @FunctionalInterface 函数式接口

1,866 阅读2分钟

在 JDK8 中,我们常用的一些接口 Callable、Runnable、Comparator 等都添加了 @FunctionalInterface 注解,那这个注解是什么意思呢?

什么是函数式接口

源码

package java.lang;

import java.lang.annotation.*;

/**
 * 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 {}

解释说明

通过 JDK8 源码 javadoc,可以知道这个注解有以下特点

  • 该注解只能标记在 "有且仅有一个抽象方法" 的接口上
  • JDK8 接口中的静态方法和默认方法,都不算是抽象方法
  • 由于所有接口默认继承 java.lang.Object,所以如果接口显示声明覆盖了 Object 中方法,那么也不算抽象方法
  • 该注解不是必须的,如果一个接口符合 "函数式接口" 定义,那么加不加该注解都没有影响。加上该注解能够更好地让编译器进行检查。如果编写的不是函数式接口,但是加上了 @FunctionInterface,那么编译器会报错。

下面这个接口就是一个正确的函数式接口:

@FunctionalInterface
public interface TestFunctionalInterface {
    // 抽象方法
    public void sub();
 
    // java.lang.Object中的方法不是抽象方法
    public boolean equals(Object var1);
 
    // default不是抽象方法
    public default void defaultMethod(){
 
    }
 
    // static不是抽象方法
    public static void staticMethod(){
 
    }
}

函数式接口的作用

首先我们定义一个普通接口和一个函数式接口

来看下将这个两个接口作为参数时,传参写法有什么不同

如上图可以看到,传入函数式接口的实例时,由于只有一个接口, ide 提示我们可以写成红框中的形式,是不是特别像是传入了一个函数(实际上传入的是一个接口的实现),这就是它为什么叫函数式接口的原因

总结:函数式接口的作用只是让接口的实现写起来像一个函数,以配合java 8 中的函数式编程