假设你有一个自定义注解@CustomAnnotation,如何通过反射在运行时动态获取该注解在方法上的参数信息?

import java.lang.annotation.*;
import java.lang.reflect.Method;

// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
    String value() default "default";
    int number() default 0;
}

// 定义一个类,并使用自定义注解
class MyClass {
    @CustomAnnotation(value = "Hello", number = 42)
    public void myMethod() {
        System.out.println("This is a method with CustomAnnotation.");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            // 获取Class对象
            Class<?> myClass = MyClass.class;

            // 获取方法对象
            Method method = myClass.getMethod("myMethod");

            // 检查方法是否被CustomAnnotation注解
            if (method.isAnnotationPresent(CustomAnnotation.class)) {
                // 获取注解实例
                CustomAnnotation annotation = method.getAnnotation(CustomAnnotation.class);

                // 获取注解参数
                String value = annotation.value();
                int number = annotation.number();

                // 打印注解参数
                System.out.println("Value: " + value);
                System.out.println("Number: " + number);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

代码说明

  1. 定义注解:

    • @Retention(RetentionPolicy.RUNTIME) 表示注解在运行时可用。
    • @Target(ElementType.METHOD) 表示注解只能用于方法上。
    • @interface 定义了注解的语法格式。
  2. 使用注解:

    • 在MyClass类的myMethod方法上使用@CustomAnnotation,并设置value和number的值。
  3. 反射获取注解:

    • 通过Class.getMethod获取方法的Method对象。
    • 使用Method.isAnnotationPresent检查方法是否被指定注解标记。
    • 使用Method.getAnnotation获取注解实例。
    • 通过注解实例直接访问其参数值。

输出结果

运行程序后,控制台将输出:

Value: Hello
Number: 42

注意事项

  • 反射操作可能会抛出异常,例如NoSuchMethodException,需要用try-catch块处理。
  • 注解的RetentionPolicy必须为RUNTIME,否则无法通过反射获取。
  • 通过反射获取注解的性能开销较高,应在必要时使用。