Annotation retention policy

In this chapter you will learn:

  1. Retention Policy
  2. How to obtaining Annotations at Run Time by Use of Reflection

Retention Policy

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

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.

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.

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//from ja v  a  2s .c om
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
  String str();

  int val();
}

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

Next chapter...

What you will learn in the next chapter:

  1. How to get all annotations
Home » Java Tutorial » Annotations
Annotations
Annotation retention policy
Annotation reflection
Annotation Default Values
Marker annotation
Single-Member Annotations
Built-In Annotations