jdk动态代理分析

1
疑问:JDK的动态代理为什么不支持对类的代理,只支持接口的代理?

jdk动态代理实例

  • 服务接口
1
2
3
4
5
6
package com.zsr.test.proxy;
public interface Hello {
public void say(String someThing);
}
  • 接口实现类
1
2
3
4
5
6
7
8
9
10
package com.zsr.test.proxy;
public class HelloImpl implements Hello {
@Override
public void say(String someThing) {
System.out.println("Hello: " + someThing);
}
}
  • 调用处理类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.zsr.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HelloInvocationHandle implements InvocationHandler {
private Object target;
public HelloInvocationHandle(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before invocation");
Object ret = method.invoke(target, args);
System.out.println("after invocation");
return ret;
}
}
  • 运行测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.zsr.test.proxy;
import java.lang.reflect.Proxy;
public class HelloProxyTest {
public static void main(String[] args) {
Hello hello = new HelloImpl();
HelloInvocationHandle helloInvocationHandler = new HelloInvocationHandle(hello);
// 通过Proxy.newProxyInstance生成代理对象
Hello helloProxy = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), hello.getClass().getInterfaces(),
helloInvocationHandler);
// 调用say方法
helloProxy.say("test");
}
}

结果:

1
2
3
Before invocation
Hello: test
after invocation

Proxy.newProxyInstance分析

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
35
36
37
38
39
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* 动态生成Class的地方,重点是看这里面的方法
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* 获取代理类的实例
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
}
}
  • 生成代理类Class
1
2
3
4
5
6
7
8
9
10
11
12
13
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// JDK对代理进行了缓存,如果已经存在相应的代理类,则直接返回,
// 否则才会通过ProxyClassFactory来创建代理
return proxyClassCache.get(loader, interfaces);
}
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
  • 代理类Class工厂
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
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// 所有代理类名字的前缀
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
......
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
// 默认情况下,代理类的完全限定名为:
// com.sun.proxy.$Proxy0,com.sun.proxy.$Proxy1依次递增
String proxyName = proxyPkg + proxyClassNamePrefix + num;
// ** 生成代理类字节码的地方 ** //
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces);
try {
// 根据二进制字节码返回相应的Class实例
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
}

反编译代理类

  • 修改测试HelloProxyTest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class HelloProxyTest {
public static void main(String[] args) {
//设置为true,会在工程根目录生成$Proxy0.class代理类(com.sun.proxy.$Proxy0.class)
System.getProperties().put(
"sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
Hello hello = new HelloImpl();
HelloInvocationHandle helloInvocationHandler = new HelloInvocationHandle(hello);
// 通过Proxy.newProxyInstance生成代理对象
Hello helloProxy = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), hello.getClass().getInterfaces(),
helloInvocationHandler);
// 调用say方法
helloProxy.say("test");
}
}

注意,当把saveGeneratedFiles属性设置为true时,生成的class文件及其所在的路径都需要提前创建,否则会抛出FileNotFoundException异常;即要在运行当前main方法的路径下创建com/sun/proxy目录,并创建一个$Proxy0.class文件

  • 反编译文件$Proxy0.class
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.sun.proxy;
import com.zsr.test.proxy.Hello;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
// ** 注意这里代理类实现了接口 ** //
public final class $Proxy0 extends Proxy
implements Hello
{
private static Method m1;
private static Method m0;
private static Method m3;
private static Method m2;
public $Proxy0(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}
public final int hashCode()
throws
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}
public final void say(String paramString)
throws
{
try
{
this.h.invoke(this, m3, new Object[] { paramString });
return;
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}
public final String toString()
throws
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
m3 = Class.forName("com.zsr.test.proxy.Hello").getMethod("say", new Class[] { Class.forName("java.lang.String") });
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
}
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}

显而易见,动态生成的代理类有如下特性:

  1. 继承了Proxy类,实现了代理的接口,由于java不能多继承,这里已经继承了Proxy类了,不能再继承其他的类,所以JDK的动态代理不支持对实现类的代理,只支持接口的代理。
  2. 代理类实现代理接口的say方法中,只是简单的调用了InvocationHandlerinvoke方法,我们可以在invoke方法中进行一些特殊操作,甚至不调用实现的方法,直接返回。

参考

JDK动态代理源码分析

热评文章