jdk动态代理的使用及实现原理

已经毕业两个月啦,在找工作的过程中经常有人问起spring相关的知识,尤其是spring核心aop是必不可少的,回答时总会回答spring的aop是由动态代理实现的,但是具体使用方法和原理有些模糊。spring提供了jdk动态代理,那么什么是jdk动态代理呢,jdk动态代理是java本身提供的一种代理实现,提供了一些实现jdk动态代理的重要类或接口在java.lang.reflect包下,如proxy类和InvocationHandler接口,我们先使用一下jdk动态代理,了解如何使用。jdk动态代理需要提供一个接口和接口的实现类,使用Proxy类的newProxyInstance方法得到生成的代理类,然后就可以调用这个代理类的方法啦。我的代码结构

 

//接口提供了一个HelloReflect方法
public interface HelloReflect { void helloReflect(); }
//接口的实现
public class HelloReflectImpl implements HelloReflect{ public void helloReflect() { System.out.println("hello reflect"); } }
JDKProxy 类继承了InvocationHandler接口,因为在Porxy类生产代理类的newProxyInstance方法中,需要三个参数,一个是类加载器,一个是实现接口的Class数组,还有一个就是InvocationHandler
的实现,重写了InvocationHandler接口的invoke方法,生成的代理类调用方法时最终会调用这个我们重写的invoke方法,在JDKProxy中还提供了一个getProxy方法里面使用newProxyInstance来获得代理类

 

 

 

public class JDKProxy implements InvocationHandler {
    private Object target;
    public JDKProxy(Object target) {
        this.target=target;
    }

    public <T> T getProxy(){
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("输出hello reflect之前");
        Object result=method.invoke(target,args);
        System.out.println("输出hello reflect之后");
        return result;
    }
}

 下面是我们测试的主方法

public class TestProxy {
    public static void main(String[] args) {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");//将生成的代理类的字节码文件保存到本地,后面分析原理会用到
        HelloReflect helloReflect1=new HelloReflectImpl();
        Class<?>[] arr=helloReflect1.getClass().getInterfaces();
        for(Class clazz:arr){
            System.out.println(clazz.getName());
        }
        HelloReflect helloReflect2=new JDKProxy(helloReflect1).getProxy();
        helloReflect2.helloReflect();
    }
}

 结果输出

 

这就是jdk动态代理的使用过程,下面进行一下原理的分析

在上面我们可以知道,我们是通过Proxy类的newProxyInstance来获取生产的代理类的,我们看一下

 

 public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        Objects.requireNonNull(h);//检查InvocationHandler是否为空

        final Class<?>[] intfs = interfaces.clone();//拷贝实现类实现的接口
        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); //获取代理类的Class对象,在这个过程中,生成代理类的字节码,并通过类加载器加载到JVN中

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

            final Constructor<?> cons = cl.getConstructor(constructorParams); //通过Class对象获取构造器
            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}); //返回实例化的代理类,并且将我们实现的InvocationHandler作为参数传入其中
        } 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);
        }
    }

 从上面可以看出来,通过getProxyClass0方法得到了代理类的Class对象,有了Class对象,我们就可以通过反射初始化代理类。因此在newProxyInstance方法中主要做了两件事

1.得到代理类的Class对象

2.通过反射得到代理类的构造器并生成代理对象,然后返回

下面我们查看得到Class对象的getProxyClass0方法

 private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }
        return proxyClassCache.get(loader, interfaces);//查看缓存中是否已经有代理类的Class对象,如果没有,进行创建
    }

 proxyClassCache.get方法中会查看缓存中是否已经存在,如果不存在,则会调用Proxy的内部类ProxyClassFactory的apply方法进行创建

 

 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);
                } 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 + "."; //ReflectUtil.PROXY_PACKAGE值为com.sun.proxy
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;//创建出来代理类的名称

            /*
             * Generate the specified proxy class.
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);  //生成代理类字节码的地方
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length); //类加载加载到JVM中
            } catch (ClassFormatError e) {
          
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

 可以看到在这类中生成了代理类的class字节码文件,并通过类加载器加载到了JVM中,可以设置将生成的字节码文件保存下来,在com.sun.proxy包下。generateProxyClass是具体生成字节码的地方,因此我们在测试的main函数中设置了System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");这样就能将生成的class文件保存下来

public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
        ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
        final byte[] var4 = var3.generateClassFile(); //生成字节码
        if (saveGeneratedFiles) { //如果设置了saveGeneratedFiles为true,则保存生成的class文件在var0下,也就是com.sun.proxy加上class文件的名称
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    try {
                        int var1 = var0.lastIndexOf(46);
                        Path var2;
                        if (var1 > 0) {
                            Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar));
                            Files.createDirectories(var3);
                            var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
                        } else {
                            var2 = Paths.get(var0 + ".class");
                        }

                        Files.write(var2, var4, new OpenOption[0]);
                        return null;
                    } catch (IOException var4x) {
                        throw new InternalError("I/O exception saving generated file: " + var4x);
                    }
                }
            });
        }

        return var4; //返回生成的字节码
    }

 

看生成的Proxy0.class文件

public final class $Proxy0 extends Proxy implements HelloReflect {
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m0;

    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);
        }
    }

    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 helloReflect() 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 { //静态代码块,默认重写了hashcode,equals,toString方法,再加上接口的方法
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m3 = Class.forName("com.jinz.reflect.HelloReflect").getMethod("helloReflect");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

 可以看到我们在调用代理类的helloReflect方法时,实际调用了我们写的InvocationHandler的invoke方法

 

 

 

 

 

整个jdk动态代理的过程就是这样了

posted @ 2020-08-29 14:40  虽为小卒  阅读(1625)  评论(0编辑  收藏  举报