What is a use case for AnnotationRetention.BINARY?

Viewed 1044

According to the Kotlin language spec, there are three types of annotation retention:

  • Source retention (accessible by source-processing tools);
  • Binary retention (retained in compilation artifacts);
  • Runtime retention (accessible at runtime).

Looking at the KDoc for kotlin-stdlib on the JVM we get the following:

public enum class AnnotationRetention {
    /** Annotation isn't stored in binary output */
    SOURCE,
    /** Annotation is stored in binary output, but invisible for reflection */
    BINARY,
    /** Annotation is stored in binary output and visible for reflection (default retention) */
    RUNTIME
}

I can understand the use cases for SOURCE (available for inspection by annotation processors) and RUNTIME (available for inspection using reflection) but I cannot understand a use case for BINARY.

Can someone please explain a use case for this type of retention? Why would I choose BINARY over SOURCE if I don't need RUNTIME?

1 Answers

As per the comment by Alexey Romanov, there is a use case for annotations outside annotation processing and runtime reflection which is shown in the answers for Java Annotations - looking for an example of RetentionPolicy.CLASS

For instance, Proguard takes .jar files and performs obfuscation and shrinking on them as per the diagram from the Proguard website below:

Proguard pipeline including input jars, shrinking, then output jars

The @Keep annotation tells Proguard not to remove a target during shrinking. This kind of annotation must be present in the binary since Proguard operates on .jar files. Since @Keep is not intended to be inspected at runtime using reflection, it would be a suitable use case for AnnotationRetention.BINARY.

Related