Java Annotation retention policy
In this chapter you will learn:
- Retention Policy
- Retention level
- Syntax for Java Annotation retention
- Example - Retention Policy.RUNTIME
- Example - How to obtaining Annotations at Run Time by Use of Reflection
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 w w w . ja v a2 s. com*/
@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.jav a 2 s . c o 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: