Packagetestannotation;Importjava.lang.annotation.Documented;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;/*** @Target describes the range of objects modified by annotation * @Retention defines the length of time that the annotation is retained * @ Documented the public API used to describe other types of annotation that should be labeled as program members*/@Documented @retention (retentionpolicy.runtime) @Target (elementtype.type) @Interfacetypeannotation {String value ()default"Defaulttypeannotation";} @Documented @retention (retentionpolicy.runtime) @Target (elementtype.method) @Interfacemethodannotation {String name ()default"Default Annotation Name"; String URL ()default"Default.com";} @Documented @retention (retentionpolicy.runtime) @Target (Elementtype.field) @Interfacefieldannotation {String value ()default"Defaultfieldannotation";} @TypeAnnotation ("Test the use of Typeannotation")classuseannotion {@FieldAnnotation (value= "Fieldannotation with value") PrivateString field; @FieldAnnotationPrivateString Fieldwithdefault; @MethodAnnotation () Public voidtestmethodannotation () {System.out.println ("Useannotion->testmethodannotation"); } @MethodAnnotation (Name= "Url=", "vip.com") Public voidTestmethodannotationwithvalue () {System.out.println ("Useannotion->testmethodannotationwithvalue"); }} Public classtestannotation { Public Static voidMain (string[] args)throwsclassnotfoundexception {Class anno= Class.forName ("Testannotation. Useannotion "); Method[] Method=Anno.getmethods (); BooleanFlag = Anno.isannotationpresent (typeannotation.class); if(flag) {typeannotation First= (typeannotation) anno.getannotation (typeannotation.class); System.out.println ("Type annotation value:" +First.value ()); } for(Method m:method) {methodannotation Methodanno=M. Getannotation (methodannotation.class); if(Methodanno = =NULL) Continue; System.out.println ("Get method Annotations \nname:\t" + methodanno.name () + "\nurl:\t" +Methodanno.url ()); } Field []field=Anno.getdeclaredfields (); for(Field f:field) {fieldannotation fieldannotation= (fieldannotation) f.getannotation (fieldannotation.class); System.out.println ("Get domain Annotations:" +Fieldannotation.value ()); } }}
Getting Started with Java annotations