设计模式——JDK动态代理原理

什么是动态代理

动态代理就是在运行时生成动态的代理对象,静态代理是通过接口,封装来实现对特定对象的代理,而动态代理则可以在运行时通过反射或者字节码来动态生成代理对象,而不仅仅只针对于特定对象。

动态代理分为两种: JDK动态代理和Cglib动态代理,前者是通过反射实现,后者是通过字节码实现,这篇博客主要讲解JDK动态代理的基本原理。

我们知道,在静态代理中,我们的代理类需要实现和被代理对象相同的接口并且聚合该代理对象,在实现重写接口方法的时候调用本身聚合的对象的实现方法从而来解决代理问题。

在JDK动态代理中,其实思想和静态代理差不多,最重要的区别只是JDK动态代理通过反射来实现静态代理,是静态模式动态化。

使用例子

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 interface Hello {
void sayHello();
}

public class HelloImpl implements Hello {
@Override
public void sayHello() {
System.out.println("Hello World");
}
}

public class MyInvocationHandler implements InvocationHandler {

private Object target;

public MyInvocationHandler(Object target) {
this.target = target;
}

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

}

public class MyDynamicProxy {
public static void main(String[] args) {
HelloImpl hello = new HelloImpl();
MyInvocationHandler handler = new MyInvocationHandler(hello);

Hello proxyHello = (Hello) Proxy.newProxyInstance(HelloImpl.class.getClassLoader(),hello.getClass().getInterfaces(),handler);

proxyHello.sayHello();
}

}

源码浅析

我们要阅读源码首先要知道整个流程大概干了什么。

我们先从使用中来猜测,我们实现了自己的InvocationHandler,这个Handler中有一个target字段,这个target指的就是被代理对象(即目标类),在被重写的invoke方法中我们通过method和args来调用target的与之对应的方法,并且在整个invoke方法中我们对它做了一些增加(即代理方法)。

我们还可以发现,我们的HelloImpl被代理类需要实现一个接口,这也是JDK动态代理的要求,毕竟它是通过接口来实现的。

在客户端主方法中我们new了一个HelloImpl对象然后将这个对象传入自己实现的InvocationHandler中,最后通过Proxy类中的newProxyInstance方法来获取代理对象,我们可以发现代理对象也是实现了Hello接口的,这和我们静态代理的实现方法是一样的!

我们再来看一下newProxyInstance方法中的三个参数。

首先第一个是ClassLoader这个就是指当前加载该类的类加载器,第二个是该类实现的接口,第三个就是handler。

最容易理解的就是handler,因为我们具体代理逻辑是写在handler中的,所以肯定要传。而interfaces是因为整个JDK动态代理需要接口的支持,我们暂且不管,这个需要后面有个整体观念。而第一个类加载器是为什么,具体用来做什么?

其实JDK动态代理就是通过传入handler和接口来通过反射来编写代理类的.java文件,然后通过编译器进行编译,最后通过类加载器load进内存。这样三个参数的作用就明了了

动态代理做主要的就是那个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
40
41
42
43
44
45
46
47
48
49
50
51
52
@CallerSensitive
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
// 其中包括获取生成.java 编译 类加载过程
/*
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs);

/*
* Invoke its constructor with the designated invocation handler.
*/
try {
// 校验
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 获取class的构造器,这里params是InvocationHandler,所以在上面的代码会给我们生成,拥有InvocationHandler对象的代理类,并且有相应的构造方法。
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
// 判断权限 如果是private 那么更改为public
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
// 通过构造器new出代理对象
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}

我们再来看一下getProxyClass0方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 这个方法传入类加载器和接口
// 注意这里没有InvocationHandler,其实也可以理解,InvocationHandler只是个接口,对于代理对象的handler字段可以写死为InvacationHandler
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {

// 如果接口数量大于多少 抛出异常
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}

// 这里值 先从缓冲中取,如果没有那么从ProxyClassFactory中制造
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}

我们来看一下ProxyClassFactory

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
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// 类的前缀
// prefix for all proxy class names
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) {

Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
for (Class<?> intf : interfaces) {
/*
* Verify that the class loader resolves the name of this
* interface to the same Class object.
*/
Class<?> interfaceClass = null;
try {
// 获取接口class
interfaceClass = Class.forName(intf.getName(), false, loader);
} catch (ClassNotFoundException e) {
}
if (interfaceClass != intf) {
throw new IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/
// 验证是否是接口
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}

// 拼接包名逻辑
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;

/*
* Record the package of a non-public proxy interface so that the
* proxy class will be defined in the same package. Verify that
* all non-public proxy interfaces are in the same package.
*/
for (Class<?> intf : interfaces) {
int flags = intf.getModifiers();
if (!Modifier.isPublic(flags)) {
accessFlags = Modifier.FINAL;
String name = intf.getName();
int n = name.lastIndexOf('.');
String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
if (proxyPkg == null) {
proxyPkg = pkg;
} else if (!pkg.equals(proxyPkg)) {
throw new IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}

if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}

/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;

/*
* Generate the specified proxy class.
*/
// 生成代理类的字节码
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
// 将字节码加载进JVM
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
/*
* A ClassFormatError here means that (barring bugs in the
* proxy class generation code) there was some other
* invalid aspect of the arguments supplied to the proxy
* class creation (such as virtual machine limitations
* exceeded).
*/
throw new IllegalArgumentException(e.toString());
}
}
}

我们来看一下生成的字节码文件

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
// 1、所有JDK动态代理  都是Proxy的子类  且自己是final类
// 2、实现了你所需要代理得接口
// 3、代理类整体看起来都是非常简单的 我们发现不管调用哪个方法,最终都是交给了InvocationHandler.invoke()方法 这也就是为什么需要我们提供这个接口的实现类的原因吧
public final class $Proxy0 extends Proxy implements Helloworld {

private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;

// 通过反射给Method赋值 这里我们得出结论
// Object的三个方法equals/toString/hashCode最终都是会被代理的
// m3是我们HelloService自己的业务方法
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("com.proxy.Helloworld").getMethod("sayHello");
m2 = Class.forName("java.lang.Object").getMethod("toString");
m0 = Class.forName("java.lang.Object").getMethod("hashCode");
} catch (NoSuchMethodException var2) {
throw new NoSuchMethodError(var2.getMessage());
} catch (ClassNotFoundException var3) {
throw new NoClassDefFoundError(var3.getMessage());
}
}
// 构造函数
// 传入了InvocationHandler
public $Proxy0(InvocationHandler var1) throws {
super(var1);
}

public final boolean equals(Object var1) throws {
try {
return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
} catch (RuntimeException | Error var3) {
throw var3;
} catch (Throwable var4) {
throw new UndeclaredThrowableException(var4);
}
}

public final void sayHello() throws {
try {
// 调用了handler的invoke方法
// 而具体的代理逻辑都在handler的invoke方法中实现
// handler中持有被代理对象 并且会在他自己的invoke中实现代理逻辑
super.h.invoke(this, m3, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}

public final String toString() throws {
try {
return (String)super.h.invoke(this, m2, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}

public final int hashCode() throws {
try {
return (Integer)super.h.invoke(this, m0, (Object[])null);
} catch (RuntimeException | Error var2) {
throw var2;
} catch (Throwable var3) {
throw new UndeclaredThrowableException(var3);
}
}
}
-------------本文结束感谢阅读-------------