import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@interface MyAnnotation {
String value() default "";
}
// 测试类
class TestClass {
@MyAnnotation("field value")
private String field;
@MyAnnotation("method value")
public void testMethod() {}
}
public class AnnotationReflectionExample {
public static void main(String[] args) {
try {
// 获取类的注解
Class<TestClass> testClass = TestClass.class;
MyAnnotation classAnnotation = testClass.getAnnotation(MyAnnotation.class);
if (classAnnotation != null) {
System.out.println("Class annotation value: " + classAnnotation.value());
}
// 获取方法的注解
Method method = testClass.getMethod("testMethod");
MyAnnotation methodAnnotation = method.getAnnotation(MyAnnotation.class);
if (methodAnnotation != null) {
System.out.println("Method annotation value: " + methodAnnotation.value());
}
// 获取字段的注解
Field field = testClass.getDeclaredField("field");
MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);
if (fieldAnnotation != null) {
System.out.println("Field annotation value: " + fieldAnnotation.value());
}
} catch (NoSuchMethodException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
- 定义自定义注解
@MyAnnotation
:
- 使用
@Retention(RetentionPolicy.RUNTIME)
确保注解在运行时可用。
- 使用
@Target
指定注解可以应用在类、方法和字段上。
- 定义一个
value
属性,默认值为空字符串。
- 定义测试类
TestClass
:
- 为字段
field
添加@MyAnnotation
注解,并设置属性值。
- 为方法
testMethod
添加@MyAnnotation
注解,并设置属性值。
- 在
main
方法中通过反射获取注解实例并打印属性值:
- 使用
Class.getAnnotation
获取类上的注解。
- 使用
Method.getAnnotation
获取方法上的注解。
- 使用
Field.getAnnotation
获取字段上的注解。
- 打印注解中的
value
属性值。