JDK之动态代理类Proxy

Wesley13
• 阅读 673

    如下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

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这