Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does @FunctionalInterface have a RUNTIME retention?

Tags:

java

java-8

Said in Javadoc:

If a type is annotated with this annotation type, compilers are required to generate an error message unless ...

Why isn't SOURCE or CLASS enough, like for @Override.

like image 350
auntyellow Avatar asked Nov 25 '14 08:11

auntyellow


People also ask

What is@ FunctionalInterface annotation?

Annotation Type 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.

What does@ FunctionalInterface do?

@FunctionalInterface annotation is used to ensure that the functional interface can't have more than one abstract method. In case more than one abstract methods are present, the compiler flags an 'Unexpected @FunctionalInterface annotation' message. However, it is not mandatory to use this annotation.

What is a FunctionalInterface java?

A functional interface in Java is an interface that contains only a single abstract (unimplemented) method. A functional interface can contain default and static methods which do have an implementation, in addition to the single unimplemented method.


2 Answers

The @FunctionalInterface annotation serves two purposes. Regarding the compiler and the error it has to generate it would be indeed enough to have a SOURCE RetentionPolicy as in this regard it only affects the very class annotated with @FunctionalInterface.

However, it has a second purpose, documenting the fact that using this interface as a functional interface is indeed intended and the possibility to use it this way not just a coincidence like with, e.g. Comparable which is not intended to be used that way.

Therefore it is annotated with @Documented and has the maximum RetentionPolicy to fulfill the second purpose.

like image 71
Holger Avatar answered Sep 18 '22 19:09

Holger


"Source" would not be enough, since if for example you create an API and provide your class as a pre-compiled jar, the information would not be available for the compiler anymore.

I believe "class" would also not be enough if you want to support those kind of compilers that "compile" against a class at runtime, like scripting engines that use reflection to find out about those annotations and should show a warning, too.

like image 23
Sebastian Avatar answered Sep 17 '22 19:09

Sebastian