Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0124 @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; @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; // 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(); } }