JDK自1.6版本就发布了动态代理类,定义为Proxy.java,主要方法为newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h),返回值是一个Object,ClassLoader为类装载器,装载动态生成的代理类,Class<?>[] 为代理类实现的接口数组,之所以用了接口数组是被代理类可能实现多个接口,所以代理类就要生成多个代理方法,InvocationHandler 代理之前或之后需要做的操作类,那Proxy的newProxyInstance方法是如何动态生成各种类的动态代理的呢,那让我们走进它的源码看看吧,看看大师们是如何做到的。
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);//判断InvocationHandler是否为空
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);//获得代理类的Class,后面着重分析这个方法
/*
* Invoke its constructor with the designated invocation handler.
*/
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);
}
}
下面着重分析下 getProxyClass0(loader, intfs)方法,源码如下:
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {//这里是控制实现接口的总数,从这里我才学到原来实现接口原来是有数量限制的,但谁能实现这么多接口啊
throw new IllegalArgumentException("interface limit exceeded");
}
// JDK的动态代理会把在生成动态代理之前会判断下这个代理是否已经生成过,
//如果已经生成过就从缓存里去,如果没有然后就生成,并把新生成的代理对象放到缓存中,以便提高效率。
return proxyClassCache.get(loader, interfaces);
}
方法proxyClassCache.get(loader, interfaces)源码如下:
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;
}
}
// 如果没有就从这里生成,subKeyFactory为初始化Proxy的一个静态变量proxyClassCache的一个参数ProxyClassFactory,并在初始化的时候已经生成对象,
// 下面我们重点分析ProxyClassFactory的apply方法,这个方法才是正在生成动态代理的地方
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
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);
}
}
}
}
ProxyClassFactory的apply方法分析
public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);//迭代实现的接口
for (Class<?> intf : interfaces) {
/*
*
* 验证这个类装载起有没有装载过这个接口生成了相同的类对象,意思就是避免重复生成接口的实现类
*/
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");
}
/*
* 判断生成的类不是接口
* .
*/
if (!interfaceClass.isInterface()) {
throw new IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* 判断生成的类不是复制,即不是克隆的
*/
if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
throw new IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // 生成代理类的默认的包名
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* 把所有生成的代理类都放到一个包下。
*
*
*/
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();
//生成的动态代理类的名字,proxyPkg为上面生成的包名,proxyClassNamePrefix为固定名字$Proxy,num为自增的数字
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* 这里通过给定的接口,代理类名字,访问权限生成动态代理类的class字节数组,
* 这里JDK通过CGlib(ASM)生成的,关于ASM的技术请参考关于java字节码框架ASM的学习
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
return defineClass0(loader, proxyName,
proxyClassFile, 0, proxyClassFile.length);//通过生成的class文件,然后生成动态代理对象。
} 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());
}
}
至此,JDK动态代理源码已经分析完毕,从中我们可以看到用到了那些技术:
1、用到了缓存技术,通过缓存加快获得动态代理类的速度。
2、生成动态代理用到了CGlib技术,在hibernate和spring中有大量的应用,其中AOP就是其中的一种应用,这与我之前写的JAVA动态代理模拟有比较大的区别,我写的那个是通过JDK提供的JavaComplier去动态编译java文件,然后在通过URLClassLoader加载字节码,我写的这个明显效率上不如JDK的动态代理模式,而且用到了反射技术,反射其实效率是很低的。
能力有限,如有分析不对的,请各位大神指出,谢谢。