Specifying a Retention Policy : Annotations Create « Language « Java Tutorial






A retention policy determines at what point an annotation is discarded.

  1. SOURCE: annotation retained only in the source file and is discarded during compilation.
  2. CLASS: annotation stored in the .class file during compilation, not available in the run time.
  3. RUNTIME: annotation stored in the .class file and available in the run time.
  4. They are defined java.lang.annotation.RetentionPolicy enumeration.

A retention policy is specified using Java's built-in annotations: @Retention.

@Retention(retention-policy)

the default policy is CLASS.

MyAnnotation uses @Retention to specify the RUNTIME retention policy.

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

// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue();

  int intValue();
}

public class MainClass {
  // Annotate a method.
  @MyAnnotation(stringValue = "Annotation Example", intValue = 100)
  public static void myMethod() {
  }

}








1.11.Annotations Create
1.11.1.Creating Annotations
1.11.2.Define new annotation type
1.11.3.Specifying a Retention Policy
1.11.4.default values in an annotation.