JDK之动态代理类Proxy

    如下List-1,动态代理生成的object是代理类,List-1的执行结果是List-2所示

    List-1

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Object object = Proxy.newProxyInstance(classLoader, new Class[]{EchoService.class}, new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (EchoService.class.isAssignableFrom(method.getDeclaringClass())) {
            return new StaticProxyEchoService(new DefaultEchoServiceImpl()).echo((String) args[0]);
        }
        return null;
    }
});
EchoService echoService = (EchoService) object;
echoService.echo("Hello world");
LOG.info(object.getClass().getSuperclass() == Proxy.class);
Class<?>[] interfaces = object.getClass().getInterfaces();
LOG.info(interfaces.length == 1);
LOG.info(interfaces[0] == EchoService.class);
Constructor<?>[] constructors = object.getClass().getConstructors();
LOG.info(constructors.length == 1);
LOG.info(constructors[0].getParameterCount() == 1);
LOG.info(constructors[0].getParameterTypes()[0] == InvocationHandler.class);

    List-2

2020-12-22 21:13:46.617 [main] INFO  com.mjduan.project.log.LOG info() 27 用时:0 
2020-12-22 21:13:46.622 [main] INFO  com.mjduan.project.log.LOG info() 27 true 
2020-12-22 21:13:46.622 [main] INFO  com.mjduan.project.log.LOG info() 27 true 
2020-12-22 21:13:46.622 [main] INFO  com.mjduan.project.log.LOG info() 27 true 
2020-12-22 21:13:46.622 [main] INFO  com.mjduan.project.log.LOG info() 27 true 
2020-12-22 21:13:46.623 [main] INFO  com.mjduan.project.log.LOG info() 27 true 
2020-12-22 21:13:46.623 [main] INFO  com.mjduan.project.log.LOG info() 27 true 

    我们可以知道object.getClass的类结构大概是如下List-3

    List-3

class $Proxy0 extends Proxy implements EchoService{

    $Proxy0(InvocationHandler handler){
       super(handler);
    }

}

    即动态生成的类object继承了Proxy,同时实现了EchoService接口,为什么继承要继承Proxy,这是因为我们自定义的InvocationHandler类实现时赋值给Proxy的属性的,如下List-4是Proxy的构造方法

    List-4

protected InvocationHandler h;

private Proxy() {
}

protected Proxy(InvocationHandler h) {
    Objects.requireNonNull(h);
    this.h = h;
}

    Proxy.newProxyInstance()的时候,如下List-5所示

1处要对传入的interfaces进行clone(),因为是数组,会被修改

2处是重点,是具体生成$Proxy的class的地方

3处获取$Proxy的构造方法,使用反射实例化

    List-5

public static Object newProxyInstance(ClassLoader loader,
                                        Class<?>[] interfaces,
                                        InvocationHandler h)
    throws IllegalArgumentException
{
    Objects.requireNonNull(h);

    final Class<?>[] intfs = interfaces.clone();//1
    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);//2

    /*
        * Invoke its constructor with the designated invocation handler.
        */
    try {
        if (sm != null) {
            checkNewProxyPermission(Reflection.getCallerClass(), cl);
        }

        final Constructor<?> cons = cl.getConstructor(constructorParams);//3
        final InvocationHandler ih = h;
        if (!Modifier.isPublic(cl.getModifiers())) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    cons.setAccessible(true);
                    return null;
                }
            });
        }
        return cons.newInstance(new Object[]{h});//4
    } 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);
    }
}

    Proxy的getProxyClass0方法如下List-6,通过WeakCache来生成class类,

    List-6

private static Class<?> getProxyClass0(ClassLoader loader,
                                        Class<?>... interfaces) {
    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);
}

    proxyClassCache的定义如下List-7所示,ProxyClassFactory是生成动态代理类的工厂

    List-7

public class Proxy implements java.io.Serializable {

    private static final long serialVersionUID = -2222568056686623797L;

    /** parameter types of a proxy class constructor */
    private static final Class<?>[] constructorParams =
        { InvocationHandler.class };

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

    如下List-8是ProxyClassFactory类的定义,会调用apply方法,这个方法里面

  •     1处需要重新加载下接口,为什么:这是因为已经加载了这些接口类不一定是传入的ClassLoader来加载的,Class.forname可以加载类,也可以控制是否初始化,这里参数是false所以不会初始化,ClassLoader.loadClass也可以加载类,但是它俩是有区别的。
  •     2处生成动态代理类的完全路径名称
  •     3处生成字节数组,ProxyGenerator.generateProxyClass__是sun包下面的
  •     4处将字节数组生成类

    List-8

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 {
                interfaceClass = Class.forName(intf.getName(), false, loader);//1
            } 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.
                */
            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.
            */
        long num = nextUniqueNumber.getAndIncrement();
        String proxyName = proxyPkg + proxyClassNamePrefix + num;//2

        /*
            * Generate the specified proxy class.
            */
        byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
            proxyName, interfaces, accessFlags);//3
        try {
            return defineClass0(loader, proxyName,
                                proxyClassFile, 0, proxyClassFile.length);//4
        } 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());
        }
    }
}

    字节码生成的$Proxy类里面,接口实现上直接调用了invocationHandler.invoke方法,见https://mp.weixin.qq.com/s/gDO6t89gqgcAglA2jkdwVQ

评论

暂无评论