Mega Code Archive

 
Categories / Java Book / 001 Language Basics
 

0126 Annotation Default Values

You can give annotation members default values. Those default value are used if no value is specified when the annotation is applied. A default value is specified by adding a default clause to a member's declaration. It has this general form: type member( ) default value; Here is @MyAnno rewritten to include default values: @Retention(RetentionPolicy.RUNTIME) @interface MyAnno { String str() default "Testing"; int val() default 9000; } Either or both can be given values if desired. Therefore, following are the four ways that @MyAnno can be used: @MyAnno() // both str and val default @MyAnno(str = "string") // val defaults @MyAnno(val = 100) // str defaults @MyAnno(str = "Testing", val = 100) // no defaults The following program demonstrates the use of default values in an annotation. import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; @Retention(RetentionPolicy.RUNTIME) @interface MyAnno { String str() default "Testing"; int val() default 1; } public class Main { @MyAnno() public static void myMeth() throws Exception{ Main ob = new Main(); Class c = ob.getClass(); Method m = c.getMethod("myMeth"); MyAnno anno = m.getAnnotation(MyAnno.class); System.out.println(anno.str() + " " + anno.val()); } public static void main(String args[]) throws Exception{ myMeth(); } }