• Java动态代理


    1、概述

    建议大家在看这篇博文之前,去我的博客中阅读Java代理模式一文。里面讲解了代理模式的相关概念。

    ①代理模式

    我们在实践过程中,常常需要对一个类的功能进行完善和增强。于是,我们经常会用继承类和实现接口的方式来增强一个类,但这样或多或少会造成类与类之间的耦合:继承类之后不能再继承其他类;实现接口的话必须实现接口中的所有方法,且若接口的方法发生改变,实现接口类也必须做出改变,这样不利于最大限度扩展。

    代理模式(Proxy)使用代理类来增强原始类。代理类需要与原始类建立逻辑关系的代码,而原始类不需要任何改动。这样有利于原始类的扩展与维护。代理模式增强原始类得到方式是非侵入性的。

    Spring AOP(Aspect Oriented Programming)就很好的体现了代理模式。

    ②动态代理

    Java动态代理就是运用了代理模式:提供一个代理类(Proxy),控制和加强原始类。说白了就是对原始类的方法的加强。

    2、Java动态代理实例分析

    UML图:

    这里写图片描述

    • Target为被代理类的接口,定义了一个operate()抽象方法。

    • ConcreteTarget为被代理类,实现了Target接口的operated()方法。

    • InvocationHandler接口为Java内置的方法处理器,用于增强被代理类的方法。

    • Handler类为InvocationHandler的实现类,用于增强被代理类。

    • Proxy为代理类,其中的静态方法newProxyInstance(ClassLoader loader, Class < ? > [] interfaces, InvocationHandler h)接受被代理类的类加载器、被代理类实现的接口、InvocationHandler的实例对象。

    ①实现Java动态代理实例基本步骤

    1. 定义被代理类接口。
    2. 定义被代理类,并实现其对应的接口方法。创建一个被代理类对象。
    3. 定义一个处理器类,并实现InvocationHandler接口。创建一个处理器对象。
    4. 通过被代理类对象,使用反射(reflect)方式获得其类加载器(ClassLoader)、接口(interfaces)。
    5. 使用Proxy类的newProxyInstance(ClassLoader loader, Class

    ②代码解析

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    /**
     * @author Hanlin Wang
     */
    
    public class DynamicProxy {
        public static void main(String[] args) {
            ConcreteTarget target = new ConcreteTarget();
    
            //获得target的类加载器。
            ClassLoader loader = target.getClass().getClassLoader();
    
            //获得target所实现的接口。
            Class<?>[] interfaces = target.getClass().getInterfaces();
    
            //创建处理器实例
            Handler handler = new Handler(target);
    
            //创建ConcreteTarget类的代理对象
            Target proxyTarget = (Target)Proxy.newProxyInstance(loader, interfaces, handler);
    
            //执行代理类方法
            proxyTarget.operate();
    
            /*
             * 运行结果:
             * 
             * 方法执行前
             * 目标方法执行!
             * 方法执行后
             */
        }
    }
    
    interface Target{
        void operate();
    }
    
    class ConcreteTarget implements Target{
        public void operate(){
            System.out.println("目标方法执行!");
        }
    }
    
    //定义处理器类,增强目标类的方法。
    class Handler implements InvocationHandler{
        private Target target;
    
        //通过构造函数注入目标类。
        public Handler(Target target) {
            this.target = target;
        }
    
        //invoke在目标类实例执行某个实现的接口的方法时自动被调用。
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("方法执行前");
    
            //调用目标类实例当前执行的方法。
            method.invoke(target, args);
    
            System.out.println("方法执行后");
    
            //根据需要,可以考虑是否需要返回值,若不需要可以返回null。
            return null;
        }
    }

    运行结果:

    方法执行前
    目标方法执行!
    方法执行后

    下面来分析一下Proxy类中的静态方法:newProxyInstance。

    public static Object newProxyInstance(ClassLoader loader,
                                              Class<?>[] interfaces,
                                              InvocationHandler h)
            throws IllegalArgumentException
        {
            if (h == null) {
                throw new NullPointerException();
            }
    
            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);
    
            /*
             * Invoke its constructor with the designated invocation handler.
             */
            try {
                final Constructor<?> cons = cl.getConstructor(constructorParams);
                final InvocationHandler ih = h;
                if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
                    // create proxy instance with doPrivilege as the proxy class may
                    // implement non-public interfaces that requires a special permission
                    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        public Object run() {
                            return newInstance(cons, ih);
                        }
                    });
                } else {
                    return newInstance(cons, ih);
                }
            } catch (NoSuchMethodException e) {
                throw new InternalError(e.toString());
            }
        }

    我们直接进入getProxyClass0方法源码:

    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的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<Object, Supplier<V>> valuesMap = map.get(cacheKey);
            if (valuesMap == null) {
                ConcurrentMap<Object, Supplier<V>> oldValuesMap
                    = map.putIfAbsent(cacheKey,
                                      valuesMap = new ConcurrentHashMap<>());
                if (oldValuesMap != null) {
                    valuesMap = oldValuesMap;
                }
            }
    
            // create subKey and retrieve the possible Supplier<V> stored by that
            // subKey from valuesMap
            Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
            Supplier<V> supplier = valuesMap.get(subKey);
            Factory factory = null;
    
            while (true) {
                if (supplier != null) {
                    // supplier might be a Factory or a CacheValue<V> instance
                    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
                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);
                    }
                }
            }
        }

    可以注意到,使用了supplier.get()方法获得代理类对象。并注意到这行:“subKeyFactory.apply(key, parameter)”,apply方法被定义在BiFunction接口中。回到Proxy类中:

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

    我们只需要关注:ProxyGenerator.generateProxyClass(
    proxyName, interfaces);(位于672行)。这一步就真正的产生了代理类对象的Binary文件了。有兴趣的同学可以使用反编译工具查看Binary文件的源码。

    ③动态代理执行过程总结

    1. 使用 InvocationHandler接口创建处理器对象
    2. 使用 Proxy 类的 newProxyInstance方法,ClassLoader 对象和一组 interface 作为参数,创建动态代理类模型。
    3. 通过反射机制获取动态代理类的构造函数,构造函数接收InvocationHandler类型的参数。
    4. 通过构造函数创建动态代理类对象,并调用处理器对象作为参数传入。
  • 相关阅读:
    ASP.NET 生命周期(原文翻译)
    JSON 小记
    Unity5-ABSystem(二):AssetBundle导出
    Unity5-ABSystem(一):AssetBundle原理
    《Unity 3D游戏客户端基础框架》概述
    Unity中的资源管理
    Unity中的优化技术
    深入浅出聊Unity3D项目优化:从Draw Calls到GC
    Incremental builds for IL2CPP
    Unity3D图像后处理特效——Depth of Field 3.4
  • 原文地址:https://www.cnblogs.com/wanxi/p/6476214.html
Copyright © 2020-2023  润新知