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