动态代理总结

一、代理模式

1.1 什么是代理模式

为其他对象提供一种代理,以控制对这个对象的访问
在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到到中介的作用

1.2 动态代理的优缺点

优点:

a. 职责清晰,只关心实际的业务逻辑,不用关心其他
b. 代理对象在在客户端和目标对象之间起到中介作用,保护目标对象
c. 高扩展性


缺点:

a. 实现比静态代理复杂,不好理解
b. 要求代理对象必须实现了某个接口
c. 不够灵活,JDK 动态代理会为接口中声明的所有方法都添加上相同的代理逻辑

二、开始:Proxy#newProxyInstance()

从 newProxyInstance() 开始

public static Object newProxyInstance(ClassLoader loader,
                                      Class<?>[] interfaces,
                                      InvocationHandler h)
	throws IllegalArgumentException
{
	// 验证传入的 InvocationHandler 不能为空
	Objects.requireNonNull(h);

	// 复制代理类要实现的所有接口
	final Class<?>[] intfs = interfaces.clone();
	// 获取安全管理器
	final SecurityManager sm = System.getSecurityManager();
	if (sm != null) {
		// 进行一些权限检验
		checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
	}

	// 关键1:获取代理类
	Class<?> cl = getProxyClass0(loader, intfs);

	try {
		if (sm != null) {
			// 进行一些权限校验
			checkNewProxyPermission(Reflection.getCallerClass(), cl);
		}

		// 获取参数类型是 InvocationHandler.class 的代理类构造器
		final Constructor<?> cons = cl.getConstructor(constructorParams);
		final InvocationHandler ih = h;
		// 如果代理类是不可访问的
		if (!Modifier.isPublic(cl.getModifiers())) {
			// 使用特权将其构造器设置为可访问
			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);
	}
}

关键1:getProxyClass0():就是用来生产代理类的类对象

private static Class<?> getProxyClass0(ClassLoader loader,
                                       Class<?>... interfaces) {
    // 当目标类实现的接口数量大于 65535
    if (interfaces.length > 65535) {
	    // 抛异常
        throw new IllegalArgumentException("interface limit exceeded");
    }
    
    // 关键2:获取代理类,使用了缓存机制
    return proxyClassCache.get(loader, interfaces);
}

关键2:通过类加载器和接口数组去缓存中获取,有则返回,无则通过工厂[ProxyClassFactory]创建

private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
	// 关键3:proxyClassCache 是类 WeakCache 的实例,因此 proxyClassCache.get() -> WeakCache#get()
	// subKeyFactory:KeyFactory
	// valueFactory:ProxyClassFactory
    proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

关键3:WeakCache#get()

// 缓存的底层实现,key 为一级缓存,value 为二级缓存,一级缓存 key 类型为 Object,支持 null
private final ConcurrentMap<Object, ConcurrentMap<Object, Supplier<V>>> map
    = new ConcurrentHashMap<>();

// key:classloader
// parameter:interfaces
public V get(K key, P parameter) {
	// 判断接口数组是否为空,为空抛异常,不为空返回接口对应类型
	Objects.requireNonNull(parameter);

	// 清除过期的缓存
	expungeStaleEntries();

	// 将传入的 classloader 包装成 CacheKey,作为一级缓存
	Object cacheKey = CacheKey.valueOf(key, refQueue);

	// 根据一级缓存 cacheKey 获取二级缓存 valuesMap
	ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
	// 如果根据 classLoader 没有获取到对应的值
	if (valuesMap == null) {
		// 以 CAS 方式放入,如果不存在则放入,否则返回原先的值
		ConcurrentMap<Object, Supplier<V>> oldValuesMap = map.putIfAbsent(cacheKey,
                              valuesMap = new ConcurrentHashMap<>());
		// 如果 oldValuesMap 有值,说明放入失败
		if (oldValuesMap != null) {
			// valuesMap 设置为原来的 oldValuesMap
			valuesMap = oldValuesMap;
		}
	}
    
    // subKeyFactory 通过 WeakCache 构造函数传入,实际为 KeyFactory
    // subKeyFactory.apply(key, parameter):KeyFactory 根据代理类实现的接口数组来生成二级缓存 key
	// Objects.requireNonNull():判断得到的二级缓存 key 是否为空,为空抛异常,不为空返回二级缓存 key 对应类型 Object
	Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
	// 根据二级缓存的 key 获取二级缓存的值 supplier
	Supplier<V> supplier = valuesMap.get(subKey);
	Factory factory = null;

	while (true) {
		// 如果二级缓存的值 supplier 不为 null
		if (supplier != null) {
			// 调用 get() 方法
			// 关键4:Factory implements Supplier,则此处实际调用的是 Factory#get()
			V value = supplier.get();
			// value 不为空
			if (value != null) {
				// 返回 value
				return value;
			}
		}
		// 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)

		// 如果 factory 等于 null
		if (factory == null) {
			// 实例化一个 Factory(作为二级缓存的值),作为 subKey (二级缓存的 key)对应的 value
			factory = new Factory(key, parameter, subKey, valuesMap);
		}

		// 如果 supplier 等于 null(根据二级缓存的 key 没有获取到二级缓存的值 supplier)
		if (supplier == null) {
			// 将实例化的 factory 作为 subKey 对应的值传入
			supplier = valuesMap.putIfAbsent(subKey, factory);
			// supplier 等于 null(可能上一步成功执行后返回的是 null???)
			if (supplier == null) {
				// successfully installed Factory
				supplier = factory;
			}
			// else retry with winning supplier
		} else { // 可能期间有其他线程修改了值,那么就不会再继续给 subKey 赋值,而是取出来直接用
			// 期间可能其它线程修改了值 factory,就用该值替换掉 supplier
			if (valuesMap.replace(subKey, supplier, factory)) {
				// 将 supplier 替换成 factory
				supplier = factory;
			} else {
				// 替换失败,继续使用原先的值
				supplier = valuesMap.get(subKey);
			}
		}
	}
}

关键4:Factory#get()

public synchronized V get() { // serialize access
    // 根据二级缓存的 key 获取 supplier
    Supplier<V> supplier = valuesMap.get(subKey);
    // 如果获取的 supplier 不是 Factory 类型
    if (supplier != this) {
        return null;
    }
    // else still us (supplier == this)

    // create new value
    V value = null;
    try {
	    // valueFactory 通过 WeakCache 构造函数传入,实际为 ProxyClassFactory
	    // 关键5:valueFactory.apply()->ProxyClassFactory#apply()
        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);

    // try replacing us with CacheValue (this should always succeed)
    if (valuesMap.replace(subKey, this, cacheValue)) {
        // put also in reverseMap
        reverseMap.put(cacheValue, Boolean.TRUE);
    } else {
        throw new AssertionError("Should not reach here");
    }

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

关键5:ProxyClassFactory#apply()

// Proxy 的类名前缀
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
    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.
         * 
         * 验证类加载器将此 interface 的名字解析成同一类对象
         */
        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.
         * 
         * 验证此接口不是重复的
         */
        // 往接口数组对应的 map 中存入类对象,返回值不为 null
        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();
        // 如果当前接口修饰符不是 public
        if (!Modifier.isPublic(flags)) {
			// 设置为 final
            accessFlags = Modifier.FINAL;
            String name = intf.getName();
            int n = name.lastIndexOf('.');
            String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
            // 包名为 null
            if (proxyPkg == null) {
	            // 包名等于当前接口的包名
                proxyPkg = pkg;
            } else if (!pkg.equals(proxyPkg)) {// 如果包名不相等
	            // 抛异常,非 public 的接口集合来自不同的包
                throw new IllegalArgumentException(
                    "non-public interfaces from different packages");
            }
        }
    }

	// 包名为 null
    if (proxyPkg == null) {
        // if no non-public proxy interfaces, use com.sun.proxy package
        // 如果 no non-public(即是 public)的代理接口集合,则使用包名 com.sun.proxy
        proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
    }

    /*
     * Choose a name for the proxy class to generate.
     */
    long num = nextUniqueNumber.getAndIncrement();
    // 组成代理类全类名:包名 + 代理类前缀 + 唯一的自增长数字
    String proxyName = proxyPkg + proxyClassNamePrefix + num;

    /*
     * Generate the specified proxy class.
     * 
     * 关键6:生成指定的代理类
     */
    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());
    }
}

关键6:生成代理类的字节码
代理类是通过 Proxy 类的 ProxyClassFactory 工厂生产,工厂会调用 ProxyGenerator#generateProxyClass() 方法生成代理类的字节码,具体是由 generateClassFile() 生成 Class 文件

最终生成的代理类:

最终生成的代理类:
public class Proxy0 extends Proxy implements IDinner {
	// 第一步:生成构造器
	protected Proxy0(InvocationHandler h) {
		super(h);
	}
	// 第二步:生成静态域
	private static Method m1; // hashCode方法
	private static Method m2; // equals方法
	private static Method m3; // toString方法
	private static Method m4; //...
	// 第三步:生成代理方法
	@Override
	public int hashCode() {
		try {
			return (int) h.invoke(this, m1, null);
		}catch (Throwable e) {
			throw new UndeclaredThrowableException(e);
		}
	}
	@Override
	public boolean equals(Object obj) {
		try {
			Object[] args = new Object[] {obj};
			return (boolean) h.invoke(this, m2, args);
		}catch (Throwable e) {
			throw new UndeclaredThrowableException(e);
		}
	}
	@Override
	public String toString() {
		try {
			return (String) h.invoke(this, m3, null);
		}catch (Throwable e) {
			throw new UndeclaredThrowableException(e);
		}
	}
	@Override
	public void dinner() {
		try {
			// 构造参数数组,如果有多个参数往后面添加就行了
			Object[] args = new Object[] {};
			// h 为通过构造方法传进来的 InvocationHandler,即此处调用 InvocationHandler#invoke(...) 方法
			h.invoke(this, m4, args);
		}catch (Throwable e) {
			throw new UndeclaredThrowableException(e);
		}
	}
	// 第四步:生成静态初始化方法
	static {
		try {
			Class c1 = Class.forName(Object.class.getName());
			Class c2 = Class.forName(IDinner.class.getName()); 
			m1 = c1.getMethod("hashCode", null);
			m2 = c1.getMethod("equals", new Class[]{Object.class});
			m3 = c1.getMethod("toString", null);
			m4 = c2.getMethod("dinner", new Class[]{IDinner.class});
			//...
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值