Defined:
Packagecom.dxz.annotation;ImportJava.lang.annotation.ElementType;Importjava.lang.annotation.Retention;ImportJava.lang.annotation.RetentionPolicy;ImportJava.lang.annotation.Target;//Defining Annotations@Target ({elementtype.type, Elementtype.field, Elementtype.method, elementtype.local_variable}) @Retention (Rete Ntionpolicy.runtime) Public@Interfacemyannotation {//define two member variablesString name ()default"Jack"; intAge ()default22;}
Test:
Packagecom.dxz.annotation;Importjava.lang.annotation.Annotation;/** Get note information Be aware that the current note must be kept at runtime * * Get Annotated Information method: * 1.getAnnotations () * Call NOTE member variable * 1. Assume the annotation object Ann, call the member variable way: Ann.name (); * 2. With Call class methods like*/ Public classTestannotationinfo { Public Static voidMain (string[] args) {Testannotationinfo Tai=NewTestannotationinfo (); Try{tai.getinfo (); } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(SecurityException e) {e.printstacktrace (); }} @MyAnnotation (name= "Zhangxun", age = 20) Public voidGetInfo ()throwsnosuchmethodexception, SecurityException {//gets all annotations contained in the GetInfo () method of the Testannotationinfo object@MyAnnotation annotation[] Annos= Testannotationinfo.class. GetMethod ("GetInfo"). Getannotations (); //traversing the Annos array for(Annotation ann:annos) {//Ann is a annotation object .//determine if the current Ann is a myannotation annotation type if(Anninstanceofmyannotation) {System.out.println (ANN); System.out.println (((myannotation) Ann). Name ()); System.out.println (((myannotation) Ann). Age ()); } } }}
Java annotations Annotation, custom annotations