Java custom annotation interface implementation scheme

  • 2020-04-01 01:09:57
  • OfStack

Java annotations are bits of meta-information that are attached to the code and used by tools to interpret and configure it at compile and run time.
Annotations do not and must not affect the actual logic of the code, and are merely auxiliary. Included in the java.lang.annotation package.
1. Meta notes
Meta-annotations are annotations of annotations. There are four: @retention @target@document@inherited.
1.1. @retention: define Retention policies for annotations
Java code
 
@Retention(RetentionPolicy.SOURCE) //Annotations exist only in the source code and are not included in the class bytecode file
@Retention(RetentionPolicy.CLASS) //By default, the annotations exist in the class bytecode file, but are not available at runtime,
@Retention(RetentionPolicy.RUNTIME)//The annotations will exist in the class bytecode file and can be retrieved by reflection at run time

1.2. @target: define the action Target of the annotation
Java code
 
@Target(ElementType.TYPE) //Interface, class, enumeration, annotation
@Target(ElementType.FIELD) //Field, constant of enumeration
@Target(ElementType.METHOD) //methods
@Target(ElementType.PARAMETER) //The method parameters
@Target(ElementType.CONSTRUCTOR) //The constructor
@Target(ElementType.LOCAL_VARIABLE)//A local variable
@Target(ElementType.ANNOTATION_TYPE)//annotations
@Target(ElementType.PACKAGE) /// package

ElementType can have multiple annotations, one for classes, methods, fields, and so on
1.3. @ Document: indicates that the annotation will be included in javadoc
1.4. @inherited: indicates that a subclass can inherit this annotation from a parent class
The following is an example of a custom annotation
2. Custom annotations
Java code
 
@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface HelloWorld { 
public String name() default ""; 
} 

3. Use of annotations and test classes
Java code
 
public class SayHello { 
@HelloWorld(name = "  Xiao Ming  ") 
public void sayHello(String name) { 
System.out.println(name + "say hello world!"); 
}//www.heatpress123.net 
} 

4. Parse annotations
Java's reflection mechanism can help, get the annotation, the code is as follows:
Java code
 
public class AnnTest { 
public void parseMethod(Class<?> clazz) { 
Object obj; 
try { 
//Create a new object with the default constructor
obj = clazz.getConstructor(new Class[] {}).newInstance( 
new Object[] {}); 
for (Method method : clazz.getDeclaredMethods()) { 
HelloWorld say = method.getAnnotation(HelloWorld.class); 
String name = ""; 
if (say != null) { 
name = say.name(); 
System.out.println(name); 
method.invoke(obj, name); 
} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 
} 
public static void main(String[] args) { 
AnnTest t = new AnnTest(); 
t.parseMethod(SayHello.class); 
} 
} 

Related articles: