jdk动态代理实现原理(JDK动态代理使用及实现原理)

 2025-08-09 17:30:01  阅读 187  评论 0

摘要:JDK 动态代理是代理模式的一种实现方式,被代理类需要实现统一接口。代理模式类图涉及核心类:java.lang.reflect.InvocationHandlerjava.lang.reflect.Proxy开发步骤1)创建统一接口2)创建接口实现类(需要代理的类)3)实现接口java.lang.reflect.InvocationHandler4)创建

JDK 动态代理是代理模式的一种实现方式,被代理类需要实现统一接口。

JDK动态代理使用及实现原理

代理模式类图

涉及核心类:

java.lang.reflect.InvocationHandlerjava.lang.reflect.Proxy

开发步骤

1)创建统一接口

2)创建接口实现类(需要代理的类)

3)实现接口java.lang.reflect.InvocationHandler

4)创建代理类并测试

demo

1)创建接口ISubject

public interface ISubject {

    void sayHello();

    String getName();
}

2)创建实现类RealSubject

public class RealSubject implements ISubject {

    private String name;

    public RealSubject(String name) {
        this.name = name;
    }

    @Override
    public void sayHello() {
        System.out.println(String.format("hello %s", name));
    }

    @Override
    public String getName() {
        return this.name;
    }
}

3)实现InvocationHandler

public class MyHandler implements InvocationHandler {

    private ISubject subject;

    public MyHandler(ISubject subject) {
        this.subject = subject;
    }

    public  T getProxy() {
        return (T) Proxy.newProxyInstance(subject.getClass().getClassLoader(), 
                subject.getClass().getInterfaces(), 
                this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //调用方法前增加业务逻辑
        System.out.println("+++++++ invoke before +++++++");
        Object res = method.invoke(subject, args);
        //调用方法后增加业务逻辑
        System.out.println("+++++++ invoke after +++++++");
        return res;
    }
}

4)测试

public class Client {
    public static void main(String[] args) {
        // 保存生成的代理类的字节码文件,在根目录生成
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        
        ISubject subject = new RealSubject("Baby");
        MyHandler handler = new MyHandler(subject);
        ISubject proxy = handler.getProxy();
        proxy.sayHello();
    }
}

运行结果:

+++++++ invoke before +++++++

hello Baby

+++++++ invoke after +++++++

源码分析

JDK版本:jdk1.8.0_121

1)Proxy类的newProxyInstance方法作为入口分析代理类构建过程

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

        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
         */
        Class cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         * 使用自定义的InvocationHandler作为参数,通过反射创建代理类实例
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }

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

2)Proxy 方法getProxyClass0()

private static Class getProxyClass0(ClassLoader loader,
                                           Class... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }
        
        //如果缓存中已经存在相应接口的代理类,直接返回;否则,使用ProxyClassFactory创建代理类
        return proxyClassCache.get(loader, interfaces);
    }

缓存proxyClassCache

//ProxyClassFactory生成代理类字节码文件
private static final WeakCache[], Class>
        proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());

3)WeakCache 的get()方法

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

        expungeStaleEntries();

        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // lazily install the 2nd level valuesMap for the particular cacheKey
        ConcurrentMap> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            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
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier supplier = valuesMap.get(subKey);
        Factory factory = null;

        while (true) {
            if (supplier != null) {
                // supplier 可能是 Factory 或者 CacheValue
                //获取代理类Class
                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
            //创建Factory,生产代理类,实际是委托给ProxyClassFactory创建
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }

4)Factory的get()方法,获取代理类Class

public synchronized V get() { // serialize access
            // re-check
            Supplier supplier = valuesMap.get(subKey);
            if (supplier != this) {
                // something changed while we were waiting:
                // might be that we were replaced by a CacheValue
                // or were removed because of failure ->
                // return null to signal WeakCache.get() to retry
                // the loop
                return null;
            }
            // else still us (supplier == this)

            // create new value
            V value = null;
            try {
                //valueFactory就是ProxyClassFactory
                //调用valueFactory.apply()创建代理类
                value = Objects.requireNonNull(valueFactory.apply(key, parameter));
            } finally {
                if (value == null) { // remove us on failure
                    valuesMap.remove(subKey, this);
                }
            }
            // the only path to reach here is with non-null value
            assert value != null;

            // 代理类Class创建成功,用 CacheValue (WeakReference) 包装
            CacheValue cacheValue = new CacheValue<>(value);

            // 缓存CacheValue,即将原来Factory替换成缓存CacheValue
            if (valuesMap.replace(subKey, this, cacheValue)) {
                // put also in reverseMap
                reverseMap.put(cacheValue, Boolean.TRUE);
            } else {
                throw new AssertionError("Should not reach here");
            }

            // successfully replaced us with new CacheValue -> return the value
            // wrapped by it
            return value;
        }

4)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.
                 */
                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) {
                // 代理类包名 com.sun.proxy 
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * Choose a name for the proxy class to generate.
             */
            long num = nextUniqueNumber.getAndIncrement();
    		//代理类全限定名称:com.sun.proxy.$Proxy+唯一数字
    		//比如demo中生成代理类:com.sun.proxy.$Proxy0
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * 生成代理类的字节码文件
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces, accessFlags);
            try {
                //类加载器将代理类的字节码文件加载到JVM中,返回Class对象
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } 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());
            }
        }

反编译代理类

// 在根目录生成的代理类的字节码文件
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

根目录下生成字节码文件:$Proxy0.class,通过反编译工具:

package com.sun.proxy;

import com.code.basic.proxy.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 m4;
    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});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void sayHello() throws  {
        try {
            //实际调用自定义的InvocationHandler执行
            super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String getName() throws  {
        try {
            return (String)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);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            //通过反射获取实现及重写的方法Method
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            //接口ISubject方法
            m4 = Class.forName("com.code.basic.proxy.ISubject").getMethod("sayHello");
            m3 = Class.forName("com.code.basic.proxy.ISubject").getMethod("getName");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

总结:

1)代理类继承了Proxy类并且实现了统一接口(ISubject),由于java不支持多继承,所以JDK动态代理必须提供统一接口。

2)代理类实现了ISubject接口定义方法,默认重写了以及Object的equals 、hashCode、toString

3)代理类实现或重写的方法,实际是调用自定义的InvocationHandler的invoke方法。

版权声明:我们致力于保护作者版权,注重分享,被刊用文章【jdk动态代理实现原理(JDK动态代理使用及实现原理)】因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!;

原文链接:https://www.yxiso.com/zhishi/2041094.html

发表评论:

关于我们
院校搜的目标不仅是为用户提供数据和信息,更是成为每一位学子梦想实现的桥梁。我们相信,通过准确的信息与专业的指导,每一位学子都能找到属于自己的教育之路,迈向成功的未来。助力每一个梦想,实现更美好的未来!
联系方式
电话:
地址:广东省中山市
Email:beimuxi@protonmail.com

Copyright © 2022 院校搜 Inc. 保留所有权利。 Powered by BEIMUCMS 3.0.3

页面耗时0.0406秒, 内存占用1.94 MB, 访问数据库24次

陕ICP备14005772号-15