JDK 动态代理源码分析

JDK动态代理,通过实现被代理类的所有接口,生成一个字节码文件后构造一个代理对象,通过持有反射构造被代理类的一个实例,再通过invoke反射调用被代理类实例的方法,来实现代理。 

代码入口Proxy.newProxyInstance():

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException {
	//handler 对象不能是空
	Objects.requireNonNull(h);

	//被代理对象实现的所有接口
	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;
		
		//如果代理对象的类或者修饰符不是 public 的, 执行 PrivilegedAction.run 方法。这里设置当前构造函数为访问权限
		if (!Modifier.isPublic(cl.getModifiers())) {
			//启用特权,执行指定的 PrivilegedAction。
			AccessController.doPrivileged(new PrivilegedAction<Void>() {
				public Void run() {
					cons.setAccessible(true);
					return null;
				}
			});
		}
		
		//使用 InvocationHandler 作为参数调用构造方法来获得代理类的实例  
		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() 源码:

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
	//class loader 实现的接口代理类定义已经存在,那么直接返回;否则通过 ProxyClassFactory 生成proxy class。(可以自己翻译)
	return proxyClassCache.get(loader, interfaces);
}
创建proxyClassCache, 是直接new 的,指定 KeyFactory 和指定 ProxyClassFactory
//两个参数要说一下:分别对应 Key工厂和代理类工厂,看名字也知道生成key 和 生成代理类class对象的
private static final WeakCache<ClassLoader, Class<?>[], Class<?>> proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

注:所以下面的 WeakCache 泛型对应:<ClassLoader, Class<?>[], Class<?>>


proxyClassCache.get() 源码

final class WeakCache<K, P, V> {   

	//
	private final ReferenceQueue<K> refQueue = new ReferenceQueue<>();

	//Map<类加载器,Map<接口数组对象key,代理类工厂Factory或代理类包装对象LookupValue>, 类加载器,已经加载的类class
	//可以把 Supplier<V> 看成生成类的class,调用get 方法就返回class
	private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map = new ConcurrentHashMap<>();

	//当前key所对应的Supplier<V> ,是否已经生成了class
	private final ConcurrentMap<Supplier<V>, Boolean> reverseMap = new ConcurrentHashMap<>();

	//创建 WeakCache 时指定的 KeyFactoryt 和 ProxyClassFactory
	private final BiFunction<K, P, ?> subKeyFactory;
	private final BiFunction<K, P, V> valueFactory;

	//参数:key:class loader,  paramer:接口class 数组
	public V get(K key, P parameter) {
		
		//判断不是null
		Objects.requireNonNull(parameter);

		//去除老的元素
		expungeStaleEntries();

		//缓存的key,hash 值计算方式为:System.identityHashCode(key)
		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) {
			//map中不存在 cacheKey,new 一个ConcurrentHashMap 放入到 map中,并返回
			ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey, valuesMap = new ConcurrentHashMap<>());
			if (oldValuesMap != null) {
				valuesMap = oldValuesMap;
			}
		}

		// create subKey and retrieve the possible Supplier<V> stored by that subKey from valuesMap
		//根据 key 生成 subKey,并在valuesMap 中查找Supplier<V>
		Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
		Supplier<V> supplier = valuesMap.get(subKey);
		
		Factory factory = null;

		while (true) {
		
			//如果supplier 在缓存中已存在,则返回。 supplier 是一个Factory 或者是 CacheValue<V>,这两个都是 Supplier 的子类。
			if (supplier != null) {
				// supplier might be a Factory or a CacheValue<V> instance
				V value = supplier.get();
				if (value != null) {
					return value;
				}
			}
			
			//如果supplier 在缓存中不存在,则生成,并放到缓存(valuesMap)中
			// 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) {
				//创建一个工厂,用来生成 supplier
				factory = new Factory(key, parameter, subKey, valuesMap);
			}

			if (supplier == null) {
				//valuesMap 是ConcurrentMap,所以在这里放入之后要再检查一遍,防止并发问题。
				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
					把 valuesMap 中的 supplier 替换为 factory
					supplier = factory;
				} else {
					// retry with current supplier
					//重新从valuesMap 获取值
					supplier = valuesMap.get(subKey);
				}
			}
		}
	}
	//省略代码.....
}
上面代码只是生成了动态代理类class的载体 Supplier<V>,获取动态代理类的class,还要看方法supplier.get(),

第一次生成动态代理类的时候 Supplier<V> 就是 Factory 对象,所以就看 Factory.get() 方法

private final class Factory implements Supplier<V> {

	//class loader
	private final K key;
	//Class[]
	private final P parameter;
	//根据key 生成的 subkey,是 valuesMap的key
	private final Object subKey;
	
	private final ConcurrentMap<Object, Supplier<V>> valuesMap;

	//省略构造函数

	@Override
	public synchronized V get() { // serialize access
		// re-check
		Supplier<V> supplier = valuesMap.get(subKey);
		if (supplier != this) {
			// something changed while we were waiting:
			// might be that we were replaced by a CacheValue
			// or were removed because of failure ->
			// return null to signal WeakCache.get() to retry
			// the loop
			//返回nul 是为了在外层(WeakCache.get()方法) 循环调用,可能会因为并发造成 supplier != this(这个Factory 是new 的)
			return null;
		}
		// else still us (supplier == this)

		// create new value
		V value = null;
		try {
			//这里才调用 valueFactory 生成动态代理类class
			//在这里又回到了 创建proxyClassCache的地方,创建proxyClassCache时指定的 ProxyClassFactory,前面做的工作都是缓存操作等。
			value = Objects.requireNonNull(valueFactory.apply(key, parameter));
		} finally {
			if (value == null) { // remove us on failure
				valuesMap.remove(subKey, this);
			}
		}
		// the only path to reach here is with non-null value
		assert value != null;

		// wrap value with CacheValue (WeakReference)
		CacheValue<V> cacheValue = new CacheValue<>(value);

		// put into reverseMap
		reverseMap.put(cacheValue, Boolean.TRUE);

		// try replacing us with CacheValue (this should always succeed)
		//缓存value 值,这里缓存的就是 CacheValue<V>
		if (!valuesMap.replace(subKey, this, cacheValue)) {
			throw new AssertionError("Should not reach here");
		}

		// successfully replaced us with new CacheValue -> return the value
		// wrapped by it
		return value;
	}
}

ProxyClassFactory.apply() 方法是如何生成动态代理类的class

//ProxyClassFactory类是 Proxy 内部类
private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>>{

	// prefix for all proxy class names
	//动态代理类类名前缀
	private static final String proxyClassNamePrefix = "$Proxy";

	// next number to use for generation of unique proxy class names
	//动态代理类类名前缀数字
	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 {
				//加载intf的 class 对象
				interfaceClass = Class.forName(intf.getName(), false, loader);
			} catch (ClassNotFoundException e) {
			}
			
			//接口的class 不是同一个class loader 加载的
			if (interfaceClass != intf) {
				throw new IllegalArgumentException(
					intf + " is not visible from class loader");
			}
			/*
			 * Verify that the Class object actually represents an
			 * interface.
			 */
			//加载intf的 不是一个接口
			if (!interfaceClass.isInterface()) {
				throw new IllegalArgumentException(
					interfaceClass.getName() + " is not an interface");
			}
			/*
			 * Verify that this interface is not a duplicate.
			 */
			//有重复的 interfaceClass
			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;

		/*
		 * 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)) {
				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.
		 */
		//生成动态代理类的类名,如:XX$Proxy1  XX$Proxy2
		long num = nextUniqueNumber.getAndIncrement();
		String proxyName = proxyPkg + proxyClassNamePrefix + num;

		/*
		 * Generate the specified proxy class.
		 */
		//生成动态代理类的字节数组
		byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);
		try {
			//根据类字节数组,加载类
			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());
		}
	}
}
生成动态代理类的字节数组  ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags)  ,生成class 实现接口所有的方法,生成一个构造方法,构造方法参数就是InvocationHandler。再继续看吧



猜你喜欢

转载自blog.csdn.net/convict_eva/article/details/80239838
今日推荐