自定义动态代理与JDK动态代理

什么是动态代理

动态代理是在运行期利用 JVM 的反射机制生成代理类,可以在不需要知道具体被代理类的情况下编写代理规则,能避免因大量使用静态代理造成的类的急剧膨胀。

自定义动态代理

MyProxy

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
package com.custom.proxy;

import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class MyProxy {

public static final String Ln = "\r\n";
public static final String Tab = "\t";

public static Object newProxyInstance(MyClassLoader loader,
Class<?>[] interfaceName,
MyInvocationHandler h) {

//1、动态生成一个.java的源文件
String proxy = generateCode(interfaceName);

//2、把生成的这个.java源文件保存在磁盘上
String filePath = MyProxy.class.getResource("").getPath();
File file = new File(filePath + "$Proxy0.java");
if (!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file);
fileWriter.write(proxy);
fileWriter.flush();

//3、把这个.java源文件编译成.class文件
// 创建一个java文件编译器对象
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// java源代码文件管理器
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
// java源文件的一个迭代器对象
Iterable iterable = fileManager.getJavaFileObjects(file);
// 获取一个编译的任务
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, iterable);
// 执行编译
task.call();
// 关闭文件管理器
fileManager.close();

//4、把编译后的.class文件加载到jvm内存中
Class clazz = loader.findClass("$Proxy0");

// 不采用自定义ClassLoader的方式加载
// URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{new URL("file:D:\\ideawork\\MySpring\\SpringDemo\\proxyCustom\\target\\classes")});
// Class clazz = urlClassLoader.loadClass("com.custom.proxy.$Proxy0");
//5、根据加载到jvm中的.class字节码文件生成Class类,然后创建Class类的对象
Constructor constructor = clazz.getConstructor(MyInvocationHandler.class);
return constructor.newInstance(h);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}



return null;
}

public static String generateCode(Class<?>[] interfances) {
StringBuffer sb = new StringBuffer();
sb.append("package com.custom.proxy;" + Ln);
sb.append("import java.lang.reflect.Method;" + Ln);
sb.append("import com.custom.proxy.MyInvocationHandler;" + Ln);
sb.append("public class $Proxy0 implements " + interfances[0].getName() + "{" + Ln);
sb.append(Tab + "private MyInvocationHandler h;" + Ln);
sb.append(Tab + "public $Proxy0(MyInvocationHandler h){" + Ln);
sb.append(Tab + Tab + "this.h = h;" + Ln);
sb.append(Tab + "}" + Ln);

for (Method m : interfances[0].getMethods()) {
sb.append(Tab + "public " + m.getReturnType().getName() + " " + m.getName() + "() {" + Ln);
sb.append(Tab + Tab + "try {" + Ln);
sb.append(Tab + Tab + Tab + "Method m = " + interfances[0].getName() + ".class.getMethod(\"" + m.getName() + "\");" + Ln);
sb.append(Tab + Tab + Tab + "h.invoke(this, m, null);" + Ln);
// sb.append(Tab + Tab + Tab + "return (" + m.getReturnType().getName() + ")h.invoke(this, m, null);" + Ln);
sb.append(Tab + Tab + "} catch (Throwable e) {" + Ln);
sb.append(Tab + Tab + Tab + "e.printStackTrace();" + Ln);
sb.append(Tab + Tab + "}" + Ln);
sb.append(Tab + "}" + Ln);
sb.append("}");
}
return sb.toString();

}
}

MyClassLoader

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
package com.custom.proxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
* 自定义一个类加载器
* bootstrap ClassLoader --jdk/jre/目录下的jar包加载
* ext ClassLoader --jdk/ext/目录下的jar包加载
* App ClassLoader --我们应用的ClassLoader
*/
public class MyClassLoader extends ClassLoader {

private File classPathFile;

public MyClassLoader() {
String classPath = MyClassLoader.class.getResource("").getPath();
this.classPathFile = new File(classPath);
}

@Override
public Class<?> findClass(String name) throws ClassNotFoundException {

if (classPathFile != null) {
File classFile = new File(classPathFile + "\\" + name.replace("\\.", "/") + ".class");

if (classFile.exists()) {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(classFile);
byte[] bytes = new byte[4096];
bos = new ByteArrayOutputStream();
int len;
while ((len = fis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
return defineClass(null, bos.toByteArray(), 0, bos.size());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

return null;
}

}

MyInvocationHandler

1
2
3
4
5
6
7
8
package com.custom.proxy;

import java.lang.reflect.Method;

public interface MyInvocationHandler {
Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
}

JDK动态代理源码分析

Object proxy = 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@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);
}

/*
* 查找或生成指定的代理类
* Look up or generate the designated proxy class.
*/
Class<?> cl = getProxyClass0(loader, intfs);

/*
* 使用指定的调用处理程序调用其构造函数
* Invoke its constructor with the designated invocation handler.
* 解释:将使用者写的InvacationHandler h 作为构造函数的参数传给代理对象
* 代理对象调用h.invoke()方法实现对target的代理和方法的增强
*/
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});
} 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);
}
}

Class<?> cl = getProxyClass0(loader, intfs);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 生成代理类。在调用之前必须调用checkProxyAccess方法来执行权限检查
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}

// 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);
}

proxyClassCache.get(loader, interfaces);

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
/**
* Look-up the value through the cache. This always evaluates the
* {@code subKeyFactory} function and optionally evaluates
* {@code valueFactory} function if there is no entry in the cache for given
* pair of (key, subKey) or the entry has already been cleared.
*
* @param key possibly null key
* @param parameter parameter used together with key to create sub-key and
* value (should not be null)
* @return the cached value (never null)
* @throws NullPointerException if {@code parameter} passed in or
* {@code sub-key} calculated by
* {@code subKeyFactory} or {@code value}
* calculated by {@code valueFactory} is null.
*/
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);

expungeStaleEntries();

Object cacheKey = CacheKey.valueOf(key, refQueue);

// lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
if (valuesMap == null) {
ConcurrentMap<Object, Supplier<V>> oldValuesMap
= map.putIfAbsent(cacheKey,
valuesMap = new ConcurrentHashMap<>());
if (oldValuesMap != null) {
valuesMap = oldValuesMap;
}
}

// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;

while (true) {
if (supplier != null) {
// supplier might be a Factory or a CacheValue<V> instance
// 这一步为获得代理对象的Class
V value = supplier.get();
if (value != null) {
return value;
}
}
// else no supplier in cache
// or a supplier that returned null (could be a cleared CacheValue
// or a Factory that wasn't successful in installing the CacheValue)

// lazily construct a Factory
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}

if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
// successfully installed Factory
supplier = factory;
}
// else retry with winning supplier
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
// successfully replaced
// cleared CacheEntry / unsuccessful Factory
// with our Factory
supplier = factory;
} else {
// retry with current supplier
supplier = valuesMap.get(subKey);
}
}
}
}

V value = supplier.get();

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
   //WeakCache的内部类
private final class Factory implements Supplier<V> {

private final K key;
private final P parameter;
private final Object subKey;
private final ConcurrentMap<Object, Supplier<V>> valuesMap;

Factory(K key, P parameter, Object subKey,
ConcurrentMap<Object, Supplier<V>> valuesMap) {
this.key = key;
this.parameter = parameter;
this.subKey = subKey;
this.valuesMap = valuesMap;
}

@Override
public synchronized V get() { // serialize access
// re-check
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
// something changed while we were waiting:
// might be that we were replaced by a CacheValue
// or were removed because of failure ->
// return null to signal WeakCache.get() to retry
// the loop
return null;
}
// else still us (supplier == this)

// create new value
V value = null;
try {
//Objects.requireNonNull()只是判断是否非空
//valueFactory.apply(key, parameter)中key为类加载器,parameter为接口的类对象
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;

// wrap value with CacheValue (WeakReference)
CacheValue<V> cacheValue = new CacheValue<>(value);

// put into reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);

// try replacing us with CacheValue (this should always succeed)
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}

// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
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
/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
* 指定类加载器和接口生成代理类.class的工厂
*/
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 {
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.
*/
//动态生成class的byte数组,通过字符串拼接jvm指令
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//将生成的byte数组加载进jvm,此方法为native方法,由C编写
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());
}
}
}

小结

  • 自定义动态代理:

    ​ 动态拼接字符串生成代理对象的.java文件 -> 将.java文件编译成.class文件 -> 通过类加载器加载.class文件进jvm -> 反射生成代理对象

  • jdk动态代理:

    ​ 生成.clsss文件的byte[]数组,直接将数组加载进jvm -> 反射生成代理对象

  • jdk动态代理无需涉及io流,所以比自定义动态代理高效。