import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;// 定义一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {String value();
}// 定义一个接口
interface MyInterface {@MyAnnotation("Hello from annotation")void doSomething();
}// 实现 InvocationHandler 接口,用于处理代理对象的方法调用
class MyInvocationHandler implements InvocationHandler {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 获取方法上的注解MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);if (annotation != null) {System.out.println("Annotation value: " + annotation.value());} else {System.out.println("No annotation found");}// 在这里可以添加自定义逻辑return null;}
}public class DynamicProxyWithAnnotation {public static void main(String[] args) {// 创建一个实例对象,该对象实现了 MyInterface 接口MyInterface myInterfaceInstance = (MyInterface) Proxy.newProxyInstance(DynamicProxyWithAnnotation.class.getClassLoader(),new Class[]{MyInterface.class},new MyInvocationHandler());// 调用接口方法myInterfaceInstance.doSomething();}
}
在这个示例中,我们定义了一个自定义注解 MyAnnotation,并将其应用在 doSomething 方法上。在 MyInvocationHandler 中,我们使用 method.getAnnotation(MyAnnotation.class) 获取方法上的注解信息,然后输出注解的值。
运行上述代码,你将看到输出中包含了注解的值,证明成功从动态代理中获取了方法上的注解信息。
请注意,注解信息是在运行时获取的,因此需要使用 RetentionPolicy.RUNTIME 保留策略。如果注解的保留策略是 RetentionPolicy.CLASS 或 RetentionPolicy.SOURCE,则在运行时无法获取到注解信息。