本文将利用Java Proxy类及代理模式 探究中的例子继续对Proxy进行探究,为了描述方便,本文现将场景描述一次。
场景:有一个接口叫超市即Supermarket,所有的超市都要实现这个接口,超市这个接口有两个方法,buy()和sell(),buy()用来进货,sell()用来销售。常见的超市有Walmart(沃尔玛),Carrefour(家乐福)等。现在当地的管理部门要对超市进行监控,需要在部分超市或者所有超市的行为进行监控。
实现:本对Supermarket接口进行代理,主要是参考了Proxy的源码,本文将jdk中Proxy类生成代理类的过程进行了简化,被简化后的Proxy类源码如下:
package java.lang.reflect;
import java.lang.reflect.Proxy.KeyFactory;
import java.lang.reflect.Proxy.ProxyClassFactory;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiFunction;
import sun.misc.ProxyGenerator;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
public class Proxy {
/**
* a cache of proxy classes
*/
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
/**
* the invocation handler for this proxy instance.
* @serial
*/
protected InvocationHandler h;
// 参数为InvocationHandler的构造方法
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
// 获取代理类
public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces){
final Class<?>[] intfs = interfaces.clone();
return getProxyClass0(loader, intfs);
}
// 获取代理类,newProxyInstance 和 getProxyClass都要调用
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) {
// 调用ProxyClassFactory 的apply, 并返回一个代理类
return proxyClassCache.get(loader, interfaces);
}
// 直接获取代理对象
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
{
Class<?> cl = getProx