动态代理实践以及底层原理分析

自Java 1.3以后,Java提供了动态代理技术,允许开发者在运行期创建接口的代理实例,后来这项技术被用到了Spring的很多地方。

JDK动态代理主要涉及java.lang.reflect包下边的两个类:Proxy和InvocationHandler。其中,InvocationHandler是一个接口,可以通过实现该接口定义横切逻辑,并通过反射机制调用目标类的代码,动态地将横切逻辑和业务逻辑编织在一起。JDK动态代理的话,他有一个限制,就是它只能为接口创建代理实例,而对于没有通过接口定义业务方法的类,如何创建动态代理实例哪?答案就是CGLib。

利用拦截器(拦截器必须实现InvocationHanlder)加上反射机制生成一个实现代理接口的匿名类,再调用具体方法前调用InvokeHandler来处理

CGLib采用底层的字节码技术,全称是:Code Generation Library,CGLib可以为一个类创建一个子类,在子类中采用方法拦截的技术拦截所有父类方法的调用并顺势织入横切逻辑。

接下来我们来一起看下这两种的使用以及原理。

 

一.JDK动态代理

  1. 使用JDK动态代理的五大步骤;

  2. 通过实现InvocationHandler接口来自定义自己的InvocationHandler;

  3. 通过Proxy.newProxyInstance获得动态代理类;

  4. 通过反射机制获得代理类的构造方法,方法签名为getConstructor(InvocationHandler.class);

  5. 通过构造函数获得代理对象并将自定义的InvocationHandler实例对象传为参数传入;

  6. 通过代理对象调用目标方法。

先看一个简单的使用实例:

package com.cjian.proxy;

/**
 * @description: 商品业务处理
 * @author: cWX969834
 * @time: 2020/10/15 9:09
 */
public interface IGoodsService {
    public String saveGoods() throws InterruptedException;
    public void updateGoods(String id) throws InterruptedException;
    public void deleteGoods(String id) throws InterruptedException;

}
package com.cjian.proxy;

/**
 * @description: 业务的具体实现
 * @author: cWX969834
 * @time: 2020/10/15 9:10
 */
public class GoodsServiceImpl implements IGoodsService {

    public String saveGoods() throws InterruptedException {
        Thread.sleep(20);//模拟业务执行时间
        System.out.println("保存商品成功!");
        return "success";
    }

    public void updateGoods(String id) throws InterruptedException {
        Thread.sleep(30);//模拟业务执行时间
        System.out.println("更新"+ id+"商品成功!");
    }

    public void deleteGoods(String id) throws InterruptedException {
        Thread.sleep(10);//模拟业务执行时间
        System.out.println("删除"+ id+"商品成功!");
    }
}
package com.cjian.proxy;

import java.util.Date;

/**
 * @description: 业务增强类
 * @author: cWX969834
 * @time: 2020/10/15 9:12
 */
public class GoodsTransaction {

    public void beginTransaction(){
        System.out.println("开启事务...");
    }
    public void commit(){
        System.out.println("提交事务...");
    }
    public long startTime() {
        return new Date().getTime();
    }
    public long endTime(){
        return new Date().getTime();
    }
}
package com.cjian.proxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * @description:
 * @author: cWX969834
 * @time: 2020/10/15 9:13
 */
public class GoodsServiceInterceptor_JDK implements InvocationHandler {
    //目标类
    private Object target;
    //增强类
    private GoodsTransaction goodsTransaction;
    //构造函数注入目标类和增强类
    public GoodsServiceInterceptor_JDK(Object target,GoodsTransaction goodsTransaction){
        this.target = target;
        this.goodsTransaction = goodsTransaction;
    }

    //代理类的每一个方法被调用的时候都会调用下边的这个invoke方法

    /**
     *
     * @param proxy 目标对象的代理类实例
     * @param method 对应于在代理实例上调用接口方法的Method实例
     * @param args  传入到代理实例方法上参数值的对象数组
     * @return 方法的返回值,没有返回值是返回null
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.goodsTransaction.beginTransaction();
        //将生成的代理对象的字节码输出到class文件
        System.out.println("方法名称:"+method.getName()+",方法参数:"+ Arrays.toString(args));
        long start = goodsTransaction.startTime();
        Object returnValue = method.invoke(this.target, args);
        long end = goodsTransaction.endTime();
        System.out.println("方法执行耗时:"+(end-start)+"ms");
        this.goodsTransaction.commit();
        return returnValue;

    }

    public static void main(String[] args)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException,
               InterruptedException {
        //将生成的代理对象大的class文件输出到class文件里
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        Object target = new GoodsServiceImpl();
        GoodsTransaction goodsTransaction = new GoodsTransaction();
        GoodsServiceInterceptor_JDK gsi = new GoodsServiceInterceptor_JDK(target, goodsTransaction);
        /*第一种方法*/
        System.out.println("============第一种方法============");
        //第一个参数设置代码使用的类加载器,一般采用跟目标类相同的类加载器
        //第二个参数设置代理类实现的接口,跟目标类使用相同的接口
        //第三个参数设置回调对象,当代理对象的方法被调用时,会调用该参数指定对象的invoke方法
        IGoodsService service = (IGoodsService)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),gsi);

        String returnValue = service.saveGoods();
        System.out.println(returnValue);

        /*第二种方法*/
        System.out.println("============第二种方法============");
        //第一个参数设置代码使用的类加载器,一般采用跟目标类相同的类加载器
        //第二个参数设置代理类实现的接口,跟目标类使用相同的接口
        Class proxyClazz = Proxy.getProxyClass(target.getClass().getClassLoader(), target.getClass().getInterfaces());
        Constructor constructor =proxyClazz.getConstructor(InvocationHandler.class);
        service = (IGoodsService) constructor.newInstance(gsi);
        returnValue = service.saveGoods();
        System.out.println(returnValue);

        System.out.println("============更新方法============");
        service.updateGoods("123");

        /**
         * 总结:
         *   1、因为利用JDKProxy生成的代理类实现了接口,所以目标类中所有的方法在代理类中都有。
         *   2、生成的代理类的所有的方法都拦截了目标类的所有的方法。而拦截器中invoke方法的内容正好就是代理类的各个方法的组成体。
         *   3、利用JDKProxy方式必须有接口的存在。
         *   4、invoke方法中的三个参数可以访问目标类的被调用方法的API、被调用方法的参数、被调用方法的返回类型。
        */

    }
}

输出结果:

============第一种方法============
开启事务...
方法名称:saveGoods,方法参数:null
保存商品成功!
方法执行耗时:21ms
提交事务...
success
============第二种方法============
开启事务...
方法名称:saveGoods,方法参数:null
保存商品成功!
方法执行耗时:21ms
提交事务...
success
============更新方法============
开启事务...
方法名称:updateGoods,方法参数:[123]
更新123商品成功!
方法执行耗时:31ms
提交事务...

源码分析

以Proxy.newProxyInstance()方法为切入点来剖析代理类的生成及代理方法的调用

 @CallerSensitive
    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.
            1.生成代理类
         */
        Class<?> cl = getProxyClass0(loader, intfs);

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

            //2.获取生成的代理类的构造函数
            //private static final Class<?>[] constructorParams ={ InvocationHandler.class }; 是类常量,作为代理类构造函数的参数类型
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            //3.返回一个代理类的实例
            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);
        }
    }

newProxyInstance()方法帮我们执行了生成代理类----获取构造器----生成代理对象这三步:

1.生成代理类: Class<?> cl = getProxyClass0(loader, intfs);

2.获取构造器: final Constructor<?> cons = cl.getConstructor(constructorParams);

3.生成代理对象: cons.newInstance(new Object[]{h});

再来详细看下这三个步骤:

1. 生成代理类: Class<?> cl = getProxyClass0(loader, intfs);

  private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        //实现的接口数不得超过65535个
        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);
    }
 public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();
        // 将ClassLoader包装成CacheKey, 作为一级缓存的key
        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
        // 根据代理类实现的接口数组来生成二级缓存key
        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);
                }
            }
        }
    }

get方法中Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));

subKeyFactory调用apply,具体实现在ProxyClassFactory中完成

private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
	    // 统一代理类的前缀名都以$Proxy
        private static final String proxyClassNamePrefix = "$Proxy";
 
        // next number to use for generation of unique proxy class names
	    // 使用唯一的编号给作为代理类名的一部分,如$Proxy0,$Proxy1等
        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.
		         * 验证指定的类加载器(loader)加载接口所得到的Class对象(interfaceClass)是否与intf对象相同
                 */
                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.
		         * 验证该Class对象是不是接口
                 */
                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
		/*如果都是public接口,那么生成的代理类就在com.sun.proxy包下如果报java.io.FileNotFoundException: com\sun\proxy\$Proxy0.class 
		(系统找不到指定的路径。)的错误,就先在你项目中创建com.sun.proxy路径*/
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }
 
            /*
             * Choose a name for the proxy class to generate.
	         * nextUniqueNumber 是一个原子类,确保多线程安全,防止类名重复,类似于: 
             * $Proxy0,$Proxy1......
             */
            long num = nextUniqueNumber.getAndIncrement();
	        // 代理类的完全限定名,如com.sun.proxy.$Proxy0.calss
            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);
            } 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()方法中

private final static boolean saveGeneratedFiles =
            java.security.AccessController.doPrivileged(
              new GetBooleanAction(
                 "sun.misc.ProxyGenerator.saveGeneratedFiles")).booleanValue();

public static byte[] generateProxyClass(final String name,
                                            Class<?>[] interfaces,
                                            int accessFlags)
    {

        // 真正生成字节码的方法
        ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
        final byte[] classFile = gen.generateClassFile();
      
        // 如果saveGeneratedFiles为true 则生成字节码文件,所以在开始我们要设置这个参数
        if (saveGeneratedFiles) {
            java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction<Void>() {
                public Void run() {
                    try {
                        int i = name.lastIndexOf('.');
                        Path path;
                        if (i > 0) {
                            Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
                            Files.createDirectories(dir);
                            path = dir.resolve(name.substring(i+1, name.length()) + ".class");
                        } else {
                            path = Paths.get(name + ".class");
                        }
                        Files.write(path, classFile);
                        return null;
                    } catch (IOException e) {
                        throw new InternalError(
                            "I/O exception saving generated file: " + e);
                    }
                }
            });
        }

        return classFile;
    }

代理类生成的最终方法是ProxyGenerator.generateClassFile()

  private byte[] generateClassFile() {

        /* ============================================================
         * Step 1: Assemble ProxyMethod objects for all methods to
         * generate proxy dispatching code for.
            步骤1:为所有方法生成代理调度代码,将代理方法对象集合起来
         */
       //通过addProxyMethod()添加hashcode、equals、toString方法
        addProxyMethod(hashCodeMethod, Object.class);
        addProxyMethod(equalsMethod, Object.class);
        addProxyMethod(toStringMethod, Object.class);

        /*
         * Now record all of the methods from the proxy interfaces, giving
         * earlier interfaces precedence over later ones with duplicate
         * methods.
           获得所有接口中的所有方法,并将方法添加到代理方法中
         */
        for (Class<?> intf : interfaces) {
            for (Method m : intf.getMethods()) {
                //往proxyMethods里put值
                addProxyMethod(m, intf);
            }
        }

        /*
         * For each set of proxy methods with the same signature,
         * verify that the methods' return types are compatible.
           验证方法签名相同的一组方法,返回值类型是否相同;意思就是重写方法要方法签名和返回值一样
         */
        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            checkReturnTypes(sigmethods);
        }

        /* ============================================================
         * Step 2: Assemble FieldInfo and MethodInfo structs for all of
         * fields and methods in the class we are generating.
           为类中的方法生成字段信息和方法信息
         */
        try {
            // 生成代理类的构造函数
            methods.add(generateConstructor());

            for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
                for (ProxyMethod pm : sigmethods) {

                    // add static field for method's Method object
                    fields.add(new FieldInfo(pm.methodFieldName,
                        "Ljava/lang/reflect/Method;",
                         ACC_PRIVATE | ACC_STATIC));

                    // generate code for proxy method and add it
                    // 生成代理类的代理方法
                    methods.add(pm.generateMethod());
                }
            }
            // 为代理类生成静态代码块,对一些字段进行初始化
            methods.add(generateStaticInitializer());

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        if (methods.size() > 65535) {
            throw new IllegalArgumentException("method limit exceeded");
        }
        if (fields.size() > 65535) {
            throw new IllegalArgumentException("field limit exceeded");
        }

        /* ============================================================
         * Step 3: Write the final class file.
          步骤3:编写最终类文件
         */

        /*
         * Make sure that constant pool indexes are reserved for the
         * following items before starting to write the final class file.
         */
        cp.getClass(dotToSlash(className));
        cp.getClass(superclassName);
        for (Class<?> intf: interfaces) {
            cp.getClass(dotToSlash(intf.getName()));
        }

        /*
         * Disallow new constant pool additions beyond this point, since
         * we are about to write the final constant pool table.
         */
        cp.setReadOnly();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);

        try {
            /*
             * Write all the items of the "ClassFile" structure.
             * See JVMS section 4.1.
             */
                                        // u4 magic;
            dout.writeInt(0xCAFEBABE);
                                        // u2 minor_version;
            dout.writeShort(CLASSFILE_MINOR_VERSION);
                                        // u2 major_version;
            dout.writeShort(CLASSFILE_MAJOR_VERSION);

            cp.write(dout);             // (write constant pool)

                                        // u2 access_flags;
            dout.writeShort(accessFlags);
                                        // u2 this_class;
            dout.writeShort(cp.getClass(dotToSlash(className)));
                                        // u2 super_class;
            dout.writeShort(cp.getClass(superclassName));

                                        // u2 interfaces_count;
            dout.writeShort(interfaces.length);
                                        // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass(
                    dotToSlash(intf.getName())));
            }

                                        // u2 fields_count;
            dout.writeShort(fields.size());
                                        // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout);
            }

                                        // u2 methods_count;
            dout.writeShort(methods.size());
                                        // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout);
            }

                                         // u2 attributes_count;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes)

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        return bout.toByteArray();
    }

生成的代理对象$Proxy0.class字节码反编译:

jdk1.8,idea,生成的字节码文件在项目的根目录下,如果找不到,可以全局搜索下(Shift+Shift)

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.sun.proxy;

import com.cjian.proxy.IGoodsService;
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 IGoodsService {
    private static Method m1;
    private static Method m2;
    private static Method m4;
    private static Method m5;
    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 updateGoods(String var1) throws InterruptedException {
        try {
            super.h.invoke(this, m4, new Object[]{var1});
        } catch (RuntimeException | InterruptedException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void deleteGoods(String var1) throws InterruptedException {
        try {
            super.h.invoke(this, m5, new Object[]{var1});
        } catch (RuntimeException | InterruptedException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String saveGoods() throws InterruptedException {
        try {
            return (String)super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | InterruptedException | 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 {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m4 = Class.forName("com.cjian.proxy.IGoodsService").getMethod("updateGoods", Class.forName("java.lang.String"));
            m5 = Class.forName("com.cjian.proxy.IGoodsService").getMethod("deleteGoods", Class.forName("java.lang.String"));
            m3 = Class.forName("com.cjian.proxy.IGoodsService").getMethod("saveGoods");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

当代理对象生成后,最后由InvocationHandler的invoke()方法调用目标方法:

在动态代理中InvocationHandler是核心,每个代理实例都具有一个关联的调用处理程序(InvocationHandler)。对代理实例调用方法时,将对方法调用进行编码并将其指派到它的调用处理程序(InvocationHandler)的invoke()方法。所以对代理方法的调用都是通InvocationHadler的invoke来实现中,而invoke方法根据传入的代理对象,方法和参数来决定调用代理的哪个方法。

       从反编译后的源码看$Proxy0类继承了Proxy类,同时实现了IGoodsServer接口,即代理类接口,所以才能强制将代理对象转换为IGoodsServer接口,然后调用$Proxy0中的saveGoods()方法

   public final String saveGoods() throws InterruptedException {
        try {
            return (String)super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | InterruptedException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

(String)super.h.invoke(this, m3, (Object[])null);

this就是$Proxy0对象;

m3就是

m3 = Class.forName("com.cjian.proxy.IGoodsService").getMethod("saveGoods");

利用全类路径名,通过反射去调用;

h就是Proxy类中的变量

/**
     * the invocation handler for this proxy instance.
     * @serial
     */
    protected InvocationHandler h;

所以成功的调到了InvocationHandler中的invoke()方法,但是invoke()方法在我们自定义的GoodsServiceInterceptor_JDK中实现,我们再来看下GoodsServiceInterceptor_JDK中的invoke()方法:

  /**
     *
     * @param proxy 目标对象的代理类实例
     * @param method 对应于在代理实例上调用接口方法的Method实例
     * @param args  传入到代理实例方法上参数值的对象数组
     * @return 方法的返回值,没有返回值是返回null
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        this.goodsTransaction.beginTransaction();
        System.out.println("方法名称:"+method.getName()+",方法参数:"+ Arrays.toString(args));
        long start = goodsTransaction.startTime();
        Object returnValue = method.invoke(this.target, args);
        long end = goodsTransaction.endTime();
        System.out.println("方法执行耗时:"+(end-start)+"ms");
        this.goodsTransaction.commit();
        return returnValue;

    }

从上面的this.h.invoke(this, m3, null)可以看出,GoodsServiceInterceptor_JDK中invoke第一个参数为$Proxy0(代理对象),第二个参数为目标类的真实方法,第三个参数为目标方法参数,因为saveGoods没有参数,所以是null。

到此jdk动态代理的底层原理分析实践完毕。

未完,后面再整理下CgLib的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值