1/** 2 * 生成一个代理类对象,
3 * Generate a proxy class. Must call the checkProxyAccess method
4 * to perform permission checks before calling this.
5*/ 6privatestatic Class<?> getProxyClass0(ClassLoader loader,
7 Class<?>... interfaces) {
8// 接口类对象数组不能大于65535个,否则抛出异常 9if (interfaces.length > 65535) {
10thrownew IllegalArgumentException("interface limit exceeded");
11 }
12// 从代理类对象缓存中,根据类加载器和接口类对象数组查找代理类对象,
13// If the proxy class defined by the given loader implementing
14// the given interfaces exists, this will simply return the cached copy;
15// otherwise, it will create the proxy class via the ProxyClassFactory16return proxyClassCache.get(loader, interfaces);
17 }
在这个方法中,是直接从一个叫proxyClassCache缓存中读取的,来看一下这个缓存的声明:
//static finalprivatestaticfinal WeakCache[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
1privatefinalclass Factory implements Supplier {
2 3privatefinal K key;
4privatefinal P parameter;
5privatefinal Object subKey;
6privatefinal ConcurrentMap> valuesMap;
7 8 Factory(K key, P parameter, Object subKey,
9 ConcurrentMap> valuesMap) {
10this.key = key;
11this.parameter = parameter;
12this.subKey = subKey;
13this.valuesMap = valuesMap;
14 }
1516 @Override
17publicsynchronized V get() { // serialize access
18// re-check
19// 检查20 Supplier supplier = valuesMap.get(subKey);
21if (supplier != this) {
22// something changed while we were waiting:
23// might be that we were replaced by a CacheValue
24// or were removed because of failure ->
25// return null to signal WeakCache.get() to retry
26// the loop27returnnull;
28 }
29// else still us (supplier == this)
3031// create new value32 V value = null;
33try {
34// valueFactory就是WeakCache的valueFactory属性,因为Factory是WeakCache的内部类,所以可以直接访问WeakCache的valueFactory属性35 value = Objects.requireNonNull(valueFactory.apply(key, parameter));
36 } finally {
37if (value == null) { // remove us on failure38 valuesMap.remove(subKey, this);
39 }
40 }
41// the only path to reach here is with non-null value42assert value != null;
4344// wrap value with CacheValue (WeakReference)45 CacheValue cacheValue = new CacheValue<>(value);
4647// try replacing us with CacheValue (this should always succeed)48if (valuesMap.replace(subKey, this, cacheValue)) {
49// put also in reverseMap50 reverseMap.put(cacheValue, Boolean.TRUE);
51 } else {
52thrownew AssertionError("Should not reach here");
53 }
5455// successfully replaced us with new CacheValue -> return the value
56// wrapped by it57return value;
58 }
59 }
1/** 2 * 一个利用给定的类加载器和接口类数组生成,定义并返回代理类对象的工厂方法
3 * A factory function that generates, defines and returns the proxy class given
4 * the ClassLoader and array of interfaces.
5*/ 6privatestaticfinalclass ProxyClassFactory
7implements BiFunction[], Class<?>>
8 {
9// prefix for all proxy class names
10// 所有代理类对象的前缀 11privatestaticfinal String proxyClassNamePrefix = "$Proxy";
12 13// next number to use for generation of unique proxy class names
14// 用于生成唯一代理类名称的下一个数字 15privatestaticfinal AtomicLong nextUniqueNumber = new AtomicLong();
16 17 @Override
18public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {
19 20 Map, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
21// 22for (Class<?> intf : interfaces) {
23/* 24 * Verify that the class loader resolves the name of this
25 * interface to the same Class object.
26*/ 27 Class<?> interfaceClass = null;
28try {
29// 加载接口类,获得接口类的类对象,第二个参数为false表示不进行实例化 30 interfaceClass = Class.forName(intf.getName(), false, loader);
31 } catch (ClassNotFoundException e) {
32 }
33if (interfaceClass != intf) {
34thrownew IllegalArgumentException(
35 intf + " is not visible from class loader");
36 }
37/* 38 * Verify that the Class object actually represents an
39 * interface.
40*/ 41if (!interfaceClass.isInterface()) {
42thrownew IllegalArgumentException(
43 interfaceClass.getName() + " is not an interface");
44 }
45/* 46 * Verify that this interface is not a duplicate.
47*/ 48if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
49thrownew IllegalArgumentException(
50 "repeated interface: " + interfaceClass.getName());
51 }
52 }
53// package to define proxy class in
54// 代理类的包名 55 String proxyPkg = null;
56int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
57 58/* 59 * Record the package of a non-public proxy interface so that the
60 * proxy class will be defined in the same package. Verify that
61 * all non-public proxy interfaces are in the same package.
62*/ 63for (Class<?> intf : interfaces) {
64int flags = intf.getModifiers();
65if (!Modifier.isPublic(flags)) {
66 accessFlags = Modifier.FINAL;
67 String name = intf.getName();
68int n = name.lastIndexOf('.');
69 String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
70if (proxyPkg == null) {
71 proxyPkg = pkg;
72 } elseif (!pkg.equals(proxyPkg)) {
73thrownew IllegalArgumentException(
74 "non-public interfaces from different packages");
75 }
76 }
77 }
78 79if (proxyPkg == null) {
80// if no non-public proxy interfaces, use com.sun.proxy package 81 proxyPkg = com.sun.proxy package 82 proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
83 }
84 85/* 86 * 生成代理类的类名
87 * Choose a name for the proxy class to generate.
88*/ 89long num = nextUniqueNumber.getAndIncrement();
90 String proxyName = proxyPkg + proxyClassNamePrefix + num;
91 92/* 93 * Generate the specified proxy class.
94*/ 95//生成代理类class文件 96byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
97try {
98// 返回代理类对象 99return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length);
100 } catch (ClassFormatError e) {
101/*102 * A ClassFormatError here means that (barring bugs in the
103 * proxy class generation code) there was some other
104 * invalid aspect of the arguments supplied to the proxy
105 * class creation (such as virtual machine limitations
106 * exceeded).
107*/108thrownew IllegalArgumentException(e.toString());
109 }
110 }
111 }
112 }