关键代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
interface Interface{
void doSth(String s);
}

class RealObject implments Interface {
void doSth(String s){
//...
}
}

class DynamicProxyHandler implments InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}

public Object invoke(Object proxy, Method m, Object[] args){
/*
在此插入代理逻辑
*/
return m.invoke(proxied, args);
}
}


public class SimpleDynamicProxy {
Interface proxy = (Interface) Proxy.newInstance(
Interface.class.getClassLoader(), //一般传这个已加载的类加载器就行
new Class[]{Interface.class}, //实现的接口
new DynamicProxyHandler(new RealObject())
);

proxy.doSth();
}

可能生成如下代理类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
final class $proxy0 extends Proxy implments Interface {

public $Proxy0(InvocationHandler var1) {
super(var1);
}

public final void doSth(String var){
try{
// 这里的h即上文传入的 new DynamicProxyHandler(new RealObject())
super.h.invoke(this, m4, new Object[]{var});
}catch{
...
}
}

static{
try{
m4=Class.forName("ProxyDemo$Interface").getMethod("doSth", Class.forName("java.lang.String"))
}catch{
...
}
}

}

Proxy 类的源码简单说:先是生成构造器,再用构造器newInstance生成动态代理对象。