动态代理-JDK Proxy 原理

上次我们讲解的cglib的动态代理的实现,今天我们看下JDK proxy的实现原理

  1. 对类Subject的方法执行前和执行后显示当前时间戳
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestProxy {
    public static interface ISubject {
        void sayHi();
    }

    public static class Subject implements ISubject {
        public void sayHi() {
            System.out.println("Subject1-sayHi");
        }
    }

    static class ProxyInvocationHandler<T> implements InvocationHandler {

        public ProxyInvocationHandler(T target) {
            this.target = target;
        }

        private T target;
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("开始时间:"+System.currentTimeMillis());
            Object result = method.invoke(target, args);
            System.out.println("结束时间:"+System.currentTimeMillis());
            return result;
        }
    }

    public static void main(String[] args) throws Exception {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        System.out.println("pid=" + runtimeMXBean.getName().split("@")[0]);

        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        ISubject subject = (ISubject) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{ISubject.class}, new ProxyInvocationHandler<ISubject>(new Subject()));
        System.out.println("ProxyInstance的类型:"+subject.getClass().getSimpleName());
        subject.sayHi();
    }
}

pid=3320
ProxyInstance的类型:$Proxy0
开始时间:1543648238358
Subject1-sayHi
结束时间:1543648238358
  1. 在1中的结果看到Proxy.newProxyInstance生成的类subject,它的类型为Proxy0,此时我们使用HSDB工具将&amp;Proxy0保存为class字节码文件或者加入开关System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");保存生成的字节码文件,反编译Proxy0代码如下:
package com.sun.proxy;

import TestProxy.ISubject;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements ISubject {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    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})).booleanValue();
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void sayHi() throws  {
        try {
            super.h.invoke(this, m3, (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 int hashCode() throws  {
        try {
            return ((Integer)super.h.invoke(this, m0, (Object[])null)).intValue();
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[]{Class.forName("java.lang.Object")});
            m3 = Class.forName("TestProxy$ISubject").getMethod("sayHi", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

  1. 原理分析
    &Proxy0实现ISubject接口,并将sayHi重写为执行InvocationHandler#invoke方法,在InvocationHandler中我们使用反射Method进行执行代码,并前后包装打印当前时间戳(反射method执行原理
  2. &Proxy0生成:ProxyGenerator.generateProxyClass生成字节码文件并使用类加载器进行加载(Proxy.newProxyInstancede的第一个参数为类加载器)他们名称就是proxyClassNamePrefix+nextUniqueNumber.getAndIncrement();
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) {
            .........
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

5.&Proxy0的方法包含hashCodeMethod,equalsMethod,toStringMethod,interfaces.getMethods()

        this.addProxyMethod(hashCodeMethod, Object.class);
        this.addProxyMethod(equalsMethod, Object.class);
        this.addProxyMethod(toStringMethod, Object.class);
        Class[] var1 = this.interfaces;
        int var2 = var1.length;

        int var3;
        Class var4;
        for(var3 = 0; var3 < var2; ++var3) {
            var4 = var1[var3];
            Method[] var5 = var4.getMethods();
            int var6 = var5.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                Method var8 = var5[var7];
                this.addProxyMethod(var8, var4);
            }
        }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容