How can we retrieve annotations on attributes in Java?
In Java, annotations on attributes can be obtained through reflection. The following are the steps for obtaining annotations on attributes.
- Get the Class object of the attribute.
- retrieve the declared field
- retrieve the annotation
Here is an example code:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
class MyClass {
@MyAnnotation("示例注解")
private String myField;
public String getMyField() {
return myField;
}
}
public class Main {
public static void main(String[] args) throws NoSuchFieldException {
MyClass obj = new MyClass();
// 获取属性对象
Class<?> cls = obj.getClass();
Field field = cls.getDeclaredField("myField");
// 获取属性上的注解对象
MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
}
}
The output shows “Example annotation,” indicating that the annotation on the property has been successfully retrieved.