java 动态代理以及自定义注解

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 {
    @Override
    public 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,则在运行时无法获取到注解信息。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值