Java - Retention Annotation Type


The Retention meta-annotation type sets how an annotation type should be retained by Java.


An annotation can be retained at three levels.

  • Source code only
  • Class file only (the default)
  • Class file and the runtime

A "source code only" retention policy will remove annotation during compiling.

"class file only" annotation cannot be read at runtime.

"class file and runtime" annotation instances are available for reading at runtime.

The Retention meta-annotation level is controlled by the java.lang.annotation.RetentionPolicy enum type.

RetentionPolicy enum has three constants

Constant Level
SOURCE source only
CLASSclass only

The following code uses the Retention meta-annotation on the Version annotation type.

It sets that the Version annotations should be available at runtime.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public @interface Version {
        int major();
        int minor();