I. Custom annotation Classes
Target limits the scope of use of annotations
TYPE,
For classes, interfaces, enumerations, but not annotations
FIELD,
field, including the enumeration value
METHOD,
methods, not including construction methods
PARAMETER,
Parameters of the method
CONSTRUCTOR,
Construction method
Local_variable,
Local variable or catch statement
Annotation_type,
Annotation type (no data) Package//java package
Retention Processing Strategy
SOURCE, //此类型会被编译器丢弃 CLASS, //此类型注解会保留在class文件中,但JVM会忽略它 RUNTIME //此类型注解会保留在class文件中,JVM会读取它
@Target (Elementtype.field) @Retention (retentionpolicy.runtime) public @Interface Name { default "Apple"; }
Two. Using annotations
Public class annottiontest { @Name ("banana") private String Name; Public String GetName () { return name; } Public void setName (String name) { this. Name = name; } }
Three. Annotation Processing class
Public classUtil { Public Static voidGetInfo (class<?>clazz) {String StrName= "Name:"; Field[] Fields=Clazz.getdeclaredfields (); for(Field field:fields) {if(Field.isannotationpresent (Name).class) {name Name= (name) field.getannotation (name).class); StrName=strname+Name.value (); System.out.println (StrName); } }} @Test Public voidFun () {util.getinfo (annottiontest).class); }}
Java Custom Annotations