java的動態代理通過Proxy的newProxyInstance方法來創建代理對象
/*
* 通過Proxy的newProxyInstance方法來創建代理對象
* 第一個參數 handler.getClass().getClassLoader() ,使用handler這個類的ClassLoader對象來加載代理對象
* 第二個參數realSubject.getClass().getInterfaces(),為代理對象提供的接口是真實對象所實行的接口,表示代理的是該真實對象,這樣就能調用這組接口中的方法了
* 第三個參數handler,將這個代理對象關聯到了上方的 InvocationHandler 這個對象上
*/
Hello helloProxy = (Hello)Proxy.newProxyInstance(handler.getClass().getClassLoader(), helloImpl
.getClass().getInterfaces(), handler);
從newProxyInstance這個入口來看看Proxy的重點方法
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//一個判空的方法
Objects.requireNonNull(h);
//將接口clone,之后對此clone類進行操作
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.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//獲取構造
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doexposingd(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);
}
}
newProxyInstance幫我們執行了生成代理類----獲取構造器----生成代理對象這三步
再來看查找/生成的代理類getProxyClass0
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
//接口數量超過65535,報異常
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);
}
/**
* a cache of proxy classes
* 動態代理類的弱緩存容器
* KeyFactory:根據接口的數量,映射一個最佳的key生成函數,其中表示接口的類對象被弱引用;
* 也就是key對象被弱引用繼承自WeakReference(key0、key1、key2、keyX),
* 保存接口密鑰(hash值)
* ProxyClassFactory:生成動態類的工廠
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
//所有代理類的名稱,在demo中打出的結果“$Proxy0”中的“$Proxy”
private static final String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class names
//每一個代理都有一個數值,在demo中打出的結果“$Proxy0”中的“0”
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;//設置一個flag,是public的或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)) {//如果接口不是public或final的
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
//proxy類所在的包名
proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
}
/*
* Choose a name for the proxy class to generate.
* 原子類,保證線程安全,防止類名重復
*/
long num = nextUniqueNumber.getAndIncrement();
//將包名與“$Proxy”,proxy類的唯一數值連接起來,就是demo中最終打出的“$Proxy0”
String proxyName = proxyPkg + proxyClassNamePrefix + num;
/*
* Generate the specified proxy class.
* 生成proxy類
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {//調用一個native方法生成
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());
}
}
}