java jdk动态代理

举例


java中动态代理主要有JDK和CGLIB两种方式。JDK代理是面向接口的代理。而CGLIB是代理类。

JDK代理的实现是通过Proxy
Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
target.getClass().getInterfaces(),InvocationHandler);为接口创建一个代理类。

通过实现InvocationHandler实现具体的代理逻辑。

创建接口

public interface PhoneService {
    void call();
}

接口实现

public class PhoneServiceImpl implements PhoneService {

    @Override
    public void call() {
        System.out.println("phone call");
    }
}

代理逻辑实现(实现InvocationHandler)

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyInvocationHandler implements InvocationHandler {
    //被代理的类
    private Object target;
    public MyInvocationHandler(Object target) {
        super();
        this.target = target;
    }
    /**
    *切面逻辑实现
    */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("phone call begin");
        Object result = method.invoke(target,args);
        System.out.println("phone call end");
        return result;
    }

    /**
     * 获取代理对象
     * @return
     */
    public Object getProxy() {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                target.getClass().getInterfaces(),this);
    }
}

测试类

public class JdkProxyTest {
    public static void main(String[] args) {
        PhoneService service = new PhoneServiceImpl();

        MyInvocationHandler handler = new MyInvocationHandler(service);

        PhoneService proxyService = (PhoneService) handler.getProxy();

        proxyService.call();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值