The @FunctionalInterface Annotation
The marker annotation @FunctionalInterface is designed to ensure that a given interface is indeed functional—that is, it contains exactly one abstract method that is either specified or inherited by the interface; otherwise, it will report an error.
@FunctionalInterface
public interface FIX { // Compiles without errors.One abstract method.
void doThings();
}
@FunctionalInterface
public interface FIXIt extends FIX { // Compiles without errors. Abstract method
} // inherited.
@FunctionalInterface
public interface FIY { // Compile-time error! More than one abstract method.
void doThings();
void doOtherThings();
}
@FunctionalInterface
public interface FIZ { // Compile-time error! No abstract method.
}
Without the @FunctionalInterface annotation, the interfaces above will compile successfully as they are all valid interface declarations. However, the presence of the @FunctionalInterface annotation will ensure that the interface has exactly one abstract method. For more details on declaring functional interfaces, see §13.1, p. 675.
It is not mandatory that all interfaces that have exactly one abstract method should be marked with the @FunctionalInterface annotation. For example, the Comparable<E> interface qualifies as a functional interface but is not marked with the @Functional-Interface annotation in the java.lang package API. Typically, only those interfaces whose implementation is provided by lambda expressions or method references are marked with this annotation. However, whether marked with this annotation or not, the compiler will treat interfaces with exactly one abstract method as functional interfaces.
The API of the FunctionalInterface annotation type from the java.lang package is shown below:
@Documented
@Retention(RUNTIME)
@Target(TYPE)
public @interface FunctionalInterface
Note that the annotation @FunctionalInterface can only be applied to a target that is a type declaration (ElementType.TYPE)—in particular, only to an interface declaration; otherwise, the compiler will flag an error. Its retention policy is RUNTIME, and therefore it is recorded in the class file and available at runtime. The javadoc tool will include the annotation in the documentation it generates, as the annotation has the meta-annotation @Documented.