JDK的Proxy类-详记2021-02-08

Proxy

首先声明,此文是我自己阅读JDK的动态代理记录的笔记,可能对你没有丝毫的帮助,请慎读。 @_@!

使用JDK提供的动态代理,需要java.lang.reflect.InvocationHandler实现.

public Object getInstance(Person target) throws Exception {
    this.target = target;
    Class clazz = this.target.getClass();
    //用来生成新的对象(使用字节码重组)
    return Proxy.newProxyInstance(clazz.getClassLoader(),
                                  clazz.getInterfaces(), this);
}

这里使用了Proxy.newProxyInstance来创建一个动态的代理类。进一步了解newProxyInstance

1.获取代理类

Class cl = getProxyClass0(loader, intfs);

2.创建代理类实例

调用构造方法,创建并返回代理类的实例

//得到构造方法
final Constructor cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Void run() {
            cons.setAccessible(true);
            return null;
        }
    });
}
return cons.newInstance(new Object[]{h});

进一步了解,是JDK如何获取代理类的

如何获取代理类

private static Class getProxyClass0(ClassLoader loader,
                                           Class... interfaces) {
    //在编译的class文件中,给类实现接口的记录只有2byte, 
    //因此,这里限制实现接口的数量不能超过这个数量 2byte = 2^16 = 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);
}

这里的ClassLoader作用是,动态重组的字节码,要动态加载到JVM上来。

get方法调用的是WeakCache中的public V get(K key, P parameter)方法。

WeakCache是Proxy中的一个静态成员

private static final WeakCache[], Class>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

实例化时, 放入了 KeyFactory,和 ProxyClassFactory

WeakCache的get方法

public V get(K key, P parameter) {
    Objects.requireNonNull(parameter);

    expungeStaleEntries();

    //构建一个缓存Key
    Object cacheKey = CacheKey.valueOf(key, refQueue);

    // lazily install the 2nd level valuesMap for the particular cacheKey
    // 从缓存中使用key获取一次
    ConcurrentMap> valuesMap = map.get(cacheKey);
    if (valuesMap == null) { 
        //如果为空时, 用当前key 创建一个 ConCurrentHashMap 并赋值给 valueMap
        ConcurrentMap> oldValuesMap
            = map.putIfAbsent(cacheKey,
                              valuesMap = new ConcurrentHashMap<>());
        if (oldValuesMap != null) {
            valuesMap = oldValuesMap;
        }
    }

    // create subKey and retrieve the possible Supplier stored by that
    // subKey from valuesMap
    // 将Parameter中的  传入的实现类接口 组成一个key 实现方式在 
    // Proxy中的内部类 KeyFactory
    Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
    // 根据这个key,获取到已经上边缓存中的 ConCurrentHashMap 这个map存的啥,进一步探究 ↓
    Supplier supplier = valuesMap.get(subKey);
    Factory factory = null;

    while (true) {
        if (supplier != null) {
            // supplier might be a Factory or a CacheValue instance
            // 这个 supplier有可能是 Factory 或者 CacheValue
            // 根据下方的代码推导,这里调用的是 Factory.get方法
            V value = supplier.get();
            if (value != null) {
                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)

        // lazily construct a Factory
        if (factory == null) {
            //懒加载 Factory
            factory = new Factory(key, parameter, subKey, valuesMap);
        }

        if (supplier == null) { //当为空时 ,给一个值
            //这里  pubIfAbsent 将subKey 和 factory放入到map,仅在subKey对应的value为空时,才put进去,否则返回一个旧的 value(Factory)
            supplier = valuesMap.putIfAbsent(subKey, factory);
            if (supplier == null) {
                // successfully installed Factory
                //将工厂赋值给 本应该从map中获取到的值上边
                supplier = factory;
            }
            // else retry with winning supplier
        } else {
            //返回一个 有 factory的 supplier ,这是个旧的Factory
            // 此处调用 替换方案 将获取出来 的 supplier 用新new的factory 替换
            /** replace 旧值为空或者 与传入的旧值是相同的时候 才进行替换,并返回旧
            的值否则返回空 */
            if (valuesMap.replace(subKey, supplier, factory)) { //当有返回值,表示                  //旧的替换成功了 则将 supplier 替换成新的factory
                // successfully replaced
                // cleared CacheEntry / unsuccessful Factory
                // with our Factory
                supplier = factory;
            } else {
                // retry with current supplier
                // 如果没替换成功,重试获取一次。并回到loop的第一行
                supplier = valuesMap.get(subKey);
            }
        }
    }
}
//模拟第二遍的流程,假设此时已经获取到了 supplier(Factory)
//调用一个Factory.get
if (supplier != null) {
    // supplier might be a Factory or a CacheValue instance
    // 这里调用 Factory的 get方法
    V value = supplier.get();
    if (value != null) {
        return value;
    }
}

KeyFactory的实现

private static final class KeyFactory
    implements BiFunction[], Object>
{
    @Override
    public Object apply(ClassLoader classLoader, Class[] interfaces) {
        switch (interfaces.length) {
            case 1: return new Key1(interfaces[0]); // the most frequent
            case 2: return new Key2(interfaces[0], interfaces[1]);
            case 0: return key0;
            default: return new KeyX(interfaces);
        }
    }
}

Factory.get()方法

@Override
public synchronized V get() { // serialize access
    // re-check
    Supplier supplier = valuesMap.get(subKey);
    if (supplier != this) {
        return null;
    }
    // else still us (supplier == this)

    // create new value
    V value = null;
    try {
        // 用传入的 ClassLoader和 需要被代理的对象,调用 valueFactory.apply方法 根据上下文
        // 可以看出 这个 valueFactory其实是 ProxyClassFactory 类型,因此,这里的apply实际上就是
        // ProxyClassFactory的 apply方法,这个方法的功能是,重组字节码,并用ClassLoader加载到 JVM然后返回
        value = Objects.requireNonNull(valueFactory.apply(key, parameter));
    } finally {
        if (value == null) { // remove us on failure
            valuesMap.remove(subKey, this);
        }
    }
    //-- 省略部分代码
    return value;
}

ProxyClassFactory 的 apply方法

public Class apply(ClassLoader loader, Class[] interfaces) {

    Map, 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. JDK要求被代理的对象一定要实现一个接口,这里确认是否为一个interface
                 */
        if (!interfaceClass.isInterface()) {
            throw new IllegalArgumentException(
                interfaceClass.getName() + " is not an interface");
        }
        /*
                 * Verify that this interface is not a duplicate.
                 * 用Map检查接口,是否实现接口重复性
                 */
        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.
             */
    //构建 代理对象的对象名称,例如 com.sun.proxy.$Proxy0这里按照JDK代理对象的规范
    // 添加上$在target对象名前边,然后用 一个计数器来标记target生成的次数
    long num = nextUniqueNumber.getAndIncrement();
    String proxyName = proxyPkg + proxyClassNamePrefix + num;

    /*
             * Generate the specified proxy class.
             */
    //调用 ProxyGenerator 重组一个 java文件的byte数组
    byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
        proxyName, interfaces, accessFlags);
    try {
        //调用类加载的方式,将byte数组动态的加载到JVM
        return defineClass0(loader, proxyName,
                            proxyClassFile, 0, proxyClassFile.length);
    } catch (ClassFormatError e) {
        throw new IllegalArgumentException(e.toString());
    }
}

按照以上丰富的操作,就是JDK实现动态代理的方式,放一个动态生成的代理类的内容

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
import org.rate.pattern.proxy.Person;

public final class $Proxy0 extends Proxy implements Person {
    //将目标类中的方法统计出来,定义到成员中
    private static Method m1;
    private static Method m4;
    private static Method m2;
    private static Method m5;
    private static Method m3;
    private static Method m0;

    //调用构造方法时,将 invocationHandler 传入到,这个变量会保存到 Proxy中的变量h
    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    /** target类的方法 1 其他就不写备注了 */
    public final void findLove() throws  {
        try {
            //调用方法时,走h也就是构造方法给的h 在结合 开头提起的
            ////用来生成新的对象(使用字节码重组) 
            //return Proxy.newProxyInstance(clazz.getClassLoader(),
            //                      clazz.getInterfaces(), this);
            // 代理类这里需要实现 InvocationHandler 并重写 Invoker方法
            // 进一步查看 重写的 invoker方法
            super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void zufangzi() throws  {
        try {
            super.h.invoke(this, m5, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void findJob() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            //类实例化的时候,会将每个方法通过反射的方式,赋值给 上边定义的成员中
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m4 = Class.forName("org.rate.pattern.proxy.Person").getMethod("findLove");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m5 = Class.forName("org.rate.pattern.proxy.Person").getMethod("zufangzi");
            m3 = Class.forName("org.rate.pattern.proxy.Person").getMethod("findJob");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

实现的代理类

public class ProxyImple implements InvocationHandler {

    private Person target;

    public Object getInstance(Person target) throws Exception {
        this.target = target;
        Class clazz = this.target.getClass();
        //用来生成新的对象(使用字节码重组)
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    //这里就是反射出来的方法 实际上, invoke的this.target可以替换成 medhos, 结果是一样的
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("方法执行前的操作1");
        System.out.println("方法执行前的操作2");
        method.invoke(this.target, args);
        System.out.println("方法执行后的操作1");
        System.out.println("方法执行后的操作2");
        return null;
    }
}

至此,JDK的动态代理源码就到此了。

你可能感兴趣的:(JDK的Proxy类-详记2021-02-08)