JDK动态代理使用的非常广泛,Spring AOP中、MyBatis的mapper中都用到了JDK动态代理。
JDK动态代理的使用
1、创建代理类接口及代理类。
2、创建一个实现了InvocationHandler接口的类,实现该接口中的invoke方法。
3、通过Proxy的newProxyInstance(ClassLoaderloader, Class[] interfaces, InvocationHandler h)方法创建一个代理对象。
来个例子:
创建一个Hello的接口
public interface Hello {
void sayHello();
}
创建一个实现了Hello接口的实现类。
public class HelloImpl implements Hello {
public void sayHello() {
System.out.println("hello");
}
}
创建一个实现了InvocationHandler接口的类。
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class HelloInvocationHandler implements InvocationHandler {
private Object hello;
public HelloInvocationHandler(Object hello) {
this.hello = hello;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("start");
Object invoke = method.invoke(hello, args);
System.out.println("end");
return invoke;
}
}
通过Proxy创建一个代理对象
Hello hello = new HelloImpl();
HelloInvocationHandler helloInvocationHandler = new HelloInvocationHandler(hello);
ClassLoader classLoader = hello.getClass().getClassLoader();
Class<?>[] interfaces = hello.getClass().getInterfaces();
Hello helloProxy = (Hello)Proxy.newProxyInstance(classLoader, interfaces, helloInvocationHandler);
helloProxy.sayHello();
看一看输出结果
start
hello
end
源码
看一下Proxy的newProxyInstance方法
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//省略
/*
* 生成代理类
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
//省略
//获取代理类的构造函数
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;
}
});
}
// 通过构造函数,将InvocationHandler设置到代理对象中,并创建代理对象
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
方法
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
return proxyClassCache.get(loader, interfaces);
}
getProxyClass0
首先判断了接口的数量,然后通过proxyClassCache
获取到了代理类,proxyClassCache
是什么东西?看一下proxyClassCache
的定义
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
通过定义可以发现,proxyClassCache
其实是一个缓存类,生成的类是放在缓存里的。接着看一个这个类的构造函数
public WeakCache(BiFunction<K, P, ?> subKeyFactory,
BiFunction<K, P, V> valueFactory) {
this.subKeyFactory = Objects.requireNonNull(subKeyFactory);
this.valueFactory = Objects.requireNonNull(valueFactory);
}
可以看到subKeyFactory
其实是KeyFactory
,valueFactory
其实是ProxyClassFactory
好了,现在回到getProxyClass0
的方法中,上面分析了proxyClassCache
了,那继续看它的get
方法
public V get(K key, P parameter) { // key 是ClassLoader parameter是interfaces
//省略
//根据ClassLoader获取cachekey
Object cacheKey = CacheKey.valueOf(key, refQueue);
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;
}
}
// 根据key 和 interfaces生成subkey
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
Supplier<V> supplier = valuesMap.get(subKey);
Factory factory = null;
while (true) {
if (supplier != null) {
V value = supplier.get();
if (value != null) {
return value;
}
}
if (factory == null) {
factory = new Factory(key, parameter, subKey, valuesMap);
}
if (supplier == null) {
supplier = valuesMap.putIfAbsent(subKey, factory);
if (supplier == null) {
supplier = factory;
}
} else {
if (valuesMap.replace(subKey, supplier, factory)) {
supplier = factory;
} else {
supplier = valuesMap.get(subKey);
}
}
}
}
这段代码看着比较绕,我们知道这个方法的作用主要是生成代理类的,那retrun value
返回的肯定是代理类,那么不妨反着推一下:
value
是supplier.get()
获取的;
supplier
其实是Factory
;
Factory
是由key
、paramter
、subkey
、valuesMap
生成的,key
和paramter
是方法入参classloader
和interfaces
;
subkey
是由subKeyFactory
跟据key
和paramter
得到的,也就是根据classloader
和interfaces
得到的;
vlauesMap
是由map
根据cacheKey
获取的,而cacheKey
是由key
得到的,也就是根据classloader
得到的。
最后,根据反推的结果再来看一边代码就好理解了,这个方法其实就是根据map
获取supplier
,只是这个map的结构比较复杂,它是一个两层的map结构:第一层的key是根据classloader
生成的一个cacheKey
对象,第二层的key是classloader
和interfaces
生成的一个subkey
对象。
接下来接着走到supplier.get()
这,看看它是怎么生成代理对象的。supplier
其实是Factory
,那就直接看Factory
的get方法
@Override
public synchronized V get() { // serialize access
Supplier<V> supplier = valuesMap.get(subKey);
if (supplier != this) {
return null;
}
V value = null;
try {
//获取代理类
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
assert value != null;
CacheValue<V> cacheValue = new CacheValue<>(value);
reverseMap.put(cacheValue, Boolean.TRUE);
if (!valuesMap.replace(subKey, this, cacheValue)) {
throw new AssertionError("Should not reach here");
}
return value;
}
}
整个方法的关键点其实在valueFactory.apply(key,paramter)
这,在前面分析中已经只知道了valueFactory
其实是ProxyClassFactory
,直接看apply
方法
@Override
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
//接口验证 省略
String proxyPkg = null; // package to define proxy class in
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
//验证接口 省略
if (proxyPkg == null) {
// if no non-public proxy interfaces, use com.sun.proxy package
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
//拼装生成的类名
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
//获取类的字节数组
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);
} catch (ClassFormatError e) {
throw new IllegalArgumentException(e.toString());
}
}
}
最后代理类是通过ProxyGenerator
生成的,具体的生成细节不再分析了,这里涉及到了很多java类字节码的知识,在ProxyGenerator
中也体现了很多字节码的东西,有兴趣的可以研究、谷歌。
既然能够得到字节数组,那么就可以把它保存成class类,反编译看一下生成的代理类代码。
//代理类类名
String className = "HelloProxy";
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
//获取代理类字节数组
byte[] data = ProxyGenerator.generateProxyClass(className, new Class[]{Hello.class},accessFlags);
FileOutputStream out;
out = null;
try {
//将代理类保存到文件
out = new FileOutputStream(className + ".class");
System.out.println((new File("HelloProxy")).getAbsolutePath());
out.write(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
反编译生成的代理类:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class HelloProxy extends Proxy implements Hello {
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
public Hello(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 {
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);
}
}
static {
try {
m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
m3 = Class.forName("Bolg.Hello").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
的invoke
方法,并传入被代理对象的方法。