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());
}
}
}
网友评论