Home > Java > javaTutorial > How to obtain and use annotation information in Java reflection?

How to obtain and use annotation information in Java reflection?

王林
Release: 2024-05-03 10:00:02
Original
1122 people have browsed it

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".

How to obtain and use annotation information in Java reflection?

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);
Copy after login

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());
}
Copy after login

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());
        }
    }
}
Copy after login

When running When executing this program, it will output:

Example annotation
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template