JDK 动态代理

本文详细介绍了JDK动态代理的实现过程,包括Proxy.newProxyInstance()的关键步骤,如Proxy类的getProxyClass0方法,WeakCache的get方法以及ProxyClassFactory的apply方法。通过示例代码和源码调试,解析了代理类的生成和实例化过程。
摘要由CSDN通过智能技术生成

1. 示例代码:

Calculator

public interface Calculator {
   
    public Integer add (Integer a, Integer b);
    public Integer sub (Integer a, Integer b);
    public Integer div (Integer a, Integer b);
    public Integer mul (Integer a, Integer b);
}

CalculatorImpl

public class CalculatorImpl implements Calculator{
   
    @Override
    public Integer add(Integer a, Integer b) {
   
        Integer result = a + b;
        return result;
    }

    @Override
    public Integer sub(Integer a, Integer b) {
   
        Integer result = a - b;
        return result;
    }

    @Override
    public Integer div(Integer a, Integer b) {
   
        Integer result = a * b;
        return result;
    }

    @Override
    public Integer mul(Integer a, Integer b) {
   
        Integer result = a / b;
        return result;
    }
}

CalProxy

public class CalProxy {
   
    public static Calculator getProxy(final Calculator calculator) {
   
        // 获取代理类的类加载器
        ClassLoader loader = calculator.getClass().getClassLoader();
        // 获取代理类的所有接口
        Class<?>[] interfaces = calculator.getClass().getInterfaces();
        // 执行代理类方法
        InvocationHandler handler = new InvocationHandler(){
   
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
   
                System.out.println("开始调用");
                Object invoke = method.invoke(calculator, args);
                System.out.println("调用结束");
                return invoke;
            }
        };
        // 生成代理对象
        Object o = Proxy.newProxyInstance(loader, interfaces, handler);
        return (Calculator) o;
    }
}

TestCal

public class TestCal {
   
    public static void main(String[] args) {
   
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        Calculator proxy = CalProxy.getProxy(new CalculatorImpl());
        proxy.add(1, 2);
        System.out.println(proxy.getClass());
    }
}

如果想要生成 class 文件的话可以添加如下参数:

// 路径,例:com.sun.proxy.$Proxy0.class
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

2. Debug 走源码

​Proxy.newProxyInstance(loader, interfaces, handler);​

CalProxy​ 类中只有 Object o = Proxy.newProxyInstance(loader, interfaces, handler);​是关键,前面的都是赋值,没有看的意义。从此句开始走源码

@CallerSensitive
    public static 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值