Java User-Defined annotation. It is convenient for programmers to obtain and process information using reflection. Let alone code.
Import static java. lang. annotation. ElementType. FIELD;
Import static java. lang. annotation. RetentionPolicy. RUNTIME;
Import java. lang. annotation. Annotation;
Import java. lang. annotation. Retention;
Import java. lang. annotation. Target;
Import java. lang. reflect. Field;
Import org. junit. Test;
Public class MyAnotation {
@ Test
Public void testMyAnotation ()
{
MySubObject mySub = new MySubObject ();
MySub. setProperty1 ("property1111 ");
MySub. setProperty2 ("property222 ");
Field [] fields = mySub. getClass (). getDeclaredFields ();
For (Field field: fields)
{
Annotation ano = field. getAnnotation (Sub. class );
If (ano! = Null)
{
System. out. println (field. getName ());
Sub sub = (Sub) ano;
System. out. println (sub. name ());
System. out. println (sub. type ());
}
}
}
@ Retention (RUNTIME)
@ Target ({FIELD })
// This annotation acts on the object's domain
Public @ interface Sub {
Public String name ();
// Name attribute
Public String type ();
// Type attribute
}
Public class MySubObject {
@ Sub (name = "mysubname", type = "mysubtype ")
Private String property1;
Private String property2;
Public String getProperty1 (){
Return property1;
}
Public void setProperty1 (String property1 ){
This. property1 = property1;
}
Public String getProperty2 (){
Return property2;
}
Public void setProperty2 (String property2 ){
This. property2 = property2;
}
}
}