6-5代理

JDK 动态代理

原理

ASM字节码操纵框架生成代理类字节码(CGLIB底层也使用ASM)
类加载器加载字节码
反射生成代理类对象并调用方法

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 定义调用处理器
class IntegerTraceHandler implements InvocationHandler {
private Integer target;

public IntegerTraceHandler(Integer target) {
this.target = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("target:" + target);
return method.invoke(target, args);
}
}

public static void main(String[] args){
Integer i = 10;
InvocationHandler handler = new IntegerTraceHandler(i);
Object proxy = Proxy.newProxyInstance(null, new Class[]{Comparable.class}, handler);
proxy.equals(1); // proxy调用IntegerTraceHandler的invoke方法
}