Home >Java >javaTutorial >How to obtain and use annotation information in Java reflection?
Java reflection can obtain annotation information. 1. Get annotation instances: Get instances of classes, methods or fields with specific annotations. 2. Use annotation information: Access the annotation member to retrieve metadata, for example, the annotation value in the class is "Example annotation".
Obtaining and using annotation information in Java reflection
Reflection is a powerful feature in Java programming, which allows the program to Check and modify the structure and behavior of classes at runtime. Reflection can also be used to obtain and use annotation information. Annotations are metadata that can be attached to classes, methods, or fields.
Get annotations
To get annotations on a class, method or field, we can use the following method:
Class<?> clazz = ...; // 获取类上带有 MyAnnotation 注解的实例 MyAnnotation classAnnotation = clazz.getAnnotation(MyAnnotation.class); // 获取方法上带有 MyAnnotation 注解的实例 Method method = ...; MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class); // 获取字段上带有 MyAnnotation 注解的实例 Field field = ...; MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);
Use annotations
After obtaining the annotation instance, we can access its members to retrieve metadata information. For example:
if (classAnnotation != null) { System.out.println("类的注解值:" + classAnnotation.value()); }
Practical example
Suppose we have a class with @MyAnnotation
annotation:
@MyAnnotation(value = "Example annotation") public class MyClass { public static void main(String[] args) { Class<?> clazz = MyClass.class; MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class); if (annotation != null) { System.out.println(annotation.value()); } } }
When running When executing this program, it will output:
Example annotation
This indicates that we successfully obtained and used the annotation information of the class.
The above is the detailed content of How to obtain and use annotation information in Java reflection?. For more information, please follow other related articles on the PHP Chinese website!