What is Java annotation retention policy

Description

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

Level

Java defines three such policies:SOURCE, CLASS, and RUNTIME.

  • SOURCE is retained only in the source file and is discarded during compilation.
  • CLASS is stored in the .class file during compilation. It is not available through the JVM during run time.
  • RUNTIME is stored in the .class file and is available through the JVM during run time.

Syntax

A retention policy is specified for an annotation by using one of Java's built-in annotations:


@Retention

Its general form is shown here:


@Retention(retention-policy)

retention-policy must be one of SOURCE, CLASS, and RUNTIME.

The default policy is CLASS.

Example

The following code specifies the Retention Policy to RUNTIME.


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//from  ww  w .  j a va 2  s.c o  m
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

Example 2

How to obtaining Annotations at Run Time by Use of Reflection.


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
/*from w  w w .j  av  a 2 s  . co  m*/
// An annotation type declaration. 
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

public class Main {
  @MyAnno(str = "Annotation Example", val = 100)
  public static void myMeth() {
    Main ob = new Main();
    try {
      Class c = ob.getClass();
      Method m = c.getMethod("myMeth");
      MyAnno anno = m.getAnnotation(MyAnno.class);
      System.out.println(anno.str() + " " + anno.val());
    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }
  public static void main(String args[]) {
    myMeth();
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures