Why does @FunctionalInterface have a RUNTIME retention?

前端 未结 3 1333
误落风尘
误落风尘 2020-12-11 15:43

Said in Javadoc:

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

相关标签:
3条回答
  • 2020-12-11 15:56

    @FunctionalInterface is for runtime reflection, compile check, and java runtime process probably.

    javap is used to de-compile and compare two interfaces, one with @FunctionalInterface, the other none.

    Just extra two lines byte code in @FunctionalInterface tagged interface:

    Constant pool:
       #7 = ...   RuntimeVisibleAnnotations
       #8 = ...   Ljava/lang/FunctionalInterface;
    

    And both implementation/lambda express are same at byte code level.

    Except for interface reflection:

    X.class.getAnnotation(FunctionalInterface.class) == null?;
    
    0 讨论(0)
  • 2020-12-11 16:13

    "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.

    0 讨论(0)
  • 2020-12-11 16:15

    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.

    0 讨论(0)
提交回复
热议问题