Not much to say, first look at the example, through the example of this custom annotation.
You define an annotation class Testtype:
Package Com.zhudan.test;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Retention (retentionpolicy.runtime) @ Target ({elementtype.type, elementtype.field,elementtype.method}) public @interface testtype {int length () default 255; String description () Default "";}
Create a user class yourself:
Package com.zhudan.test;/* * */public class TestUser {@testType (length=50,description= "name") Private stringname;@ Testtype (length=50,description= "age") Private stringage;public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getage () {return age;} public void Setage (String age) {this.age = age;}}
Test class tests:
Package Com.zhudan.test;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;public Class Test {public static void main (string[] args) throws Illegalargumentexception,illegalaccessexception, invocationtargetexception {field[] fields = TestUser.class.getDeclaredFields (); for (Field Field:fields) { System.out.println (field);//Get the Custom annotation class Testtype type = Field.getannotation (testtype.class); int s=type.length (); String ss=type.description (); SYSTEM.OUT.PRINTLN (ss); int Lengstring=type.length (); System.out.println (lengstring);}}}
The effect is as follows:
Custom annotations, of course, this is just a small demo, I just want to use this little demo to tell myself the benefits of custom annotations, how to use, the most basic method is what, a little bit, for further understanding to prepare.
Java Custom Annotations and interpretation