//从interfaces可以看出,动态代理可以同时实现多个接口
public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces)
throws IllegalArgumentException {
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
if (interfaces == null) {
throw new NullPointerException("interfaces == null");
}
final List<Class<?>> interfaceList = new ArrayList<Class<?>>(interfaces.length);
Collections.addAll(interfaceList, interfaces);
final Set<Class<?>> interfaceSet = new HashSet<Class<?>>(interfaceList);
if (interfaceSet.contains(null)) {
throw new NullPointerException("interface list contains null: " + interfaceList);
}
if (interfaceSet.size() != interfaces.length) {
throw new IllegalArgumentException("duplicate interface in list: " + interfaceList);
}
//查看缓存中是否已经存在代理类
synchronized (loader.proxyCache) {
Class<?> proxy = loader.proxyCache.get(interfaceList);
if (proxy != null) {
return proxy;
}
}
String commonPackageName = null;
for (Class<?> c : interfaces) {
//被代理类必须是接口类,这点感觉不好,如果任何类都可以代理那就很爽了
if (!c.isInterface()) {
throw new IllegalArgumentException(c + " is not an interface");
}
if (!isVisibleToClassLoader(loader, c)) {
throw new IllegalArgumentException(c + " is not visible from class loader");
},
if (!Modifier.isPublic(c.getModifiers())) {
String packageName = c.getPackageName$();
if (packageName == null) {
packageName = "";
}
if (commonPackageName != null && !commonPackageName.equals(packageName)) {
throw new IllegalArgumentException(
"non-public interfaces must be in the same package");
}
commonPackageName = packageName;
}
}
//可以看出改代码是获取所有接口的方法属性
List<Method> methods = getMethods(interfaces);
Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
validateReturnTypes(methods);
List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);
Method[] methodsArray = methods.toArray(new Method[methods.size()]);
Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);
//生成代理类的包名
String baseName = commonPackageName != null && !commonPackageName.isEmpty()
? commonPackageName + ".$Proxy"
: "$Proxy";
Class<?> result;
synchronized (loader.proxyCache) {
result = loader.proxyCache.get(interfaceList);
if (result == null) {
String name = baseName + nextClassNameIndex++;
//生成Class文件并生成代理类Class对象。
result = generateProxy(name, interfaces, loader, methodsArray, exceptionsArray);
loader.proxyCache.put(interfaceList, result);
}
}
return result;
}