jdk8動態(tài)代理源碼分析

JDK動態(tài)代理的實現(xiàn)原理

1)通過實現(xiàn)InvocationHandler接口來自定義自己的InvocationHandler;
2)通過Proxy.getProxyClass獲得動態(tài)代理類;
3)通過反射機制獲得代理類的構(gòu)造方法,方法簽名getConstructor(InvocationHandler.class);
4)通過構(gòu)造函數(shù)獲得代理對象并將自定義的InvocationHandler實例對象傳為參數(shù)傳入;
5)通過代理對象調(diào)用目標(biāo)方法;

IHello接口

package com.jpeony.spring.proxy.jdk;
 
public interface IHello {
    void sayHello();
}

HelloImpl接口實現(xiàn)

package com.jpeony.spring.proxy.jdk;
 
public class HelloImpl implements IHello {
    @Override
    public void sayHello() {
        System.out.println("Hello world!");
    }
}

MyInvocationHandler(實現(xiàn)InvocationHandler接口)

package com.jpeony.spring.proxy.jdk;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
 
public class MyInvocationHandler implements InvocationHandler {
 
    /** 目標(biāo)對象 */
    private Object target;
 
    public MyInvocationHandler(Object target){
        this.target = target;
    }
 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("------插入前置通知代碼-------------");
        // 執(zhí)行相應(yīng)的目標(biāo)方法
        Object rs = method.invoke(target,args);
        System.out.println("------插入后置處理代碼-------------");
        return rs;
    }
}

MyProxyTest(Client)

package com.jpeony.spring.proxy.jdk;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
 
/**
 * 使用JDK動態(tài)代理的五大步驟:
 * 1.通過實現(xiàn)InvocationHandler接口來自定義自己的InvocationHandler;
 * 2.通過Proxy.getProxyClass獲得動態(tài)代理類
 * 3.通過反射機制獲得代理類的構(gòu)造方法,方法簽名為getConstructor(InvocationHandler.class)
 * 4.通過構(gòu)造函數(shù)獲得代理對象并將自定義的InvocationHandler實例對象傳為參數(shù)傳入
 * 5.通過代理對象調(diào)用目標(biāo)方法
 */
public class MyProxyTest {
    public static void main(String[] args)
            throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        // =========================第一種==========================
        // 1、生成$Proxy0的class文件
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        // 2、獲取動態(tài)代理類
        Class proxyClazz = Proxy.getProxyClass(IHello.class.getClassLoader(),IHello.class);
        // 3、獲得代理類的構(gòu)造函數(shù),并傳入?yún)?shù)類型InvocationHandler.class
        Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
        // 4、通過構(gòu)造函數(shù)來創(chuàng)建動態(tài)代理對象,將自定義的InvocationHandler實例傳入
        IHello iHello1 = (IHello) constructor.newInstance(new MyInvocationHandler(new HelloImpl()));
        // 5、通過代理對象調(diào)用目標(biāo)方法
        iHello1.sayHello();
 
        // ==========================第二種=============================
        /**
         * Proxy類中還有個將2~4步驟封裝好的簡便方法來創(chuàng)建動態(tài)代理對象,
         *其方法簽名為:newProxyInstance(ClassLoader loader,Class<?>[] instance, InvocationHandler h)
         */
        IHello  iHello2 = (IHello) Proxy.newProxyInstance(IHello.class.getClassLoader(), // 加載接口的類加載器
                new Class[]{IHello.class}, // 一組接口
                new MyInvocationHandler(new HelloImpl())); // 自定義的InvocationHandler
        iHello2.sayHello();
    }
}
image.png

源碼分析

以Proxy.newProxyInstance()方法為切入點來剖析代理類的生成及代理方法的調(diào)用。

@CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
    // 如果h為空直接拋出空指針異常,之后所有的單純的判斷null并拋異常,都是此方法
        Objects.requireNonNull(h);
    // 拷貝類實現(xiàn)的所有接口
        final Class<?>[] intfs = interfaces.clone();
    // 獲取當(dāng)前系統(tǒng)安全接口
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
        // Reflection.getCallerClass返回調(diào)用該方法的方法的調(diào)用類;loader:接口的類加載器
        // 進行包訪問權(quán)限、類加載器權(quán)限等檢查
            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.
     * 譯: 用指定的調(diào)用處理程序調(diào)用它的構(gòu)造函數(shù)。
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
       /*
        * 獲取代理類的構(gòu)造函數(shù)對象。
        * constructorParams是類常量,作為代理類構(gòu)造函數(shù)的參數(shù)類型,常量定義如下:
        * 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;
                    }
                });
            }
        // 根據(jù)代理類的構(gòu)造函數(shù)對象來創(chuàng)建需要返回的代理類對象
            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()方法幫我們執(zhí)行了生成代理類----獲取構(gòu)造器----生成代理對象這三步;

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

獲取構(gòu)造器: final Constructor<?> cons = cl.getConstructor(constructorParams);

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

Proxy.getProxyClass0()如何生成代理類?

private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
    // 接口數(shù)不得超過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
    // 譯: 如果緩存中有代理類了直接返回,否則將由代理類工廠ProxyClassFactory創(chuàng)建代理類
        return proxyClassCache.get(loader, interfaces);
    }

如果緩存中沒有代理類,Proxy中的ProxyClassFactory如何創(chuàng)建代理類?從get()方法追蹤進去看看。

public V get(K key, P parameter) {// key:類加載器;parameter:接口數(shù)組
        // 檢查指定類型的對象引用不為空null。當(dāng)參數(shù)為null時,拋出空指針異常。
        Objects.requireNonNull(parameter);
        // 清除已經(jīng)被GC回收的弱引用
        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);
        // 沒有獲取到對應(yīng)的值
        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
        // 根據(jù)代理類實現(xiàn)的接口數(shù)組來生成二級緩存key
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        // 通過subKey獲取二級緩存值
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;
        // 這個循環(huán)提供了輪詢機制, 如果條件為假就繼續(xù)重試直到條件為真為止
        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                // 在這里supplier可能是一個Factory也可能會是一個CacheValue
                // 在這里不作判斷, 而是在Supplier實現(xiàn)類的get方法里面進行驗證
                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實例作為subKey對應(yīng)的值
                factory = new Factory(key, parameter, subKey, valuesMap);
            }
 
            if (supplier == null) {
                // 到這里表明subKey沒有對應(yīng)的值, 就將factory作為subKey的值放入
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    // 到這里表明成功將factory放入緩存
                    supplier = factory;
                }
                // 否則, 可能期間有其他線程修改了值, 那么就不再繼續(xù)給subKey賦值, 而是取出來直接用
                // else retry with winning supplier
            } else {
                // 期間可能其他線程修改了值, 那么就將原先的值替換
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    // 成功將factory替換成新的值
                    supplier = factory;
                } else {
                    // retry with current supplier
                    // 替換失敗, 繼續(xù)使用原先的值
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }

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

subKeyFactory調(diào)用apply,具體實現(xiàn)在ProxyClassFactory中完成。

ProxyClassFactory.apply()實現(xiàn)代理類創(chuàng)建。

private static final class ProxyClassFactory
        implements BiFunction<ClassLoader, Class<?>[], Class<?>>
    {
        // prefix for all proxy class names
    // 統(tǒng)一代理類的前綴名都以$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.
         * 驗證該接口是否重復(fù)
                 */
                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.
         * 驗證所有非公共的接口在同一個包內(nèi);公共的就無需處理
             */
            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 
        (系統(tǒng)找不到指定的路徑。)的錯誤,就先在你項目中創(chuàng)建com.sun.proxy路徑*/
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }
 
            /*
             * Choose a name for the proxy class to generate.
         * nextUniqueNumber 是一個原子類,確保多線程安全,防止類名重復(fù),類似于:$Proxy0,$Proxy1......
             */
            long num = nextUniqueNumber.getAndIncrement();
        // 代理類的完全限定名,如com.sun.proxy.$Proxy0.calss
            String proxyName = proxyPkg + proxyClassNamePrefix + num;
 
            /*
             * Generate the specified proxy class.
         * 生成類字節(jié)碼的方法(重點)
             */
            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());
            }
        }
    }

代理類創(chuàng)建真正在ProxyGenerator.generateProxyClass()方法中,方法簽名如下:

byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);

public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
        ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
        // 真正生成字節(jié)碼的方法
        final byte[] classFile = gen.generateClassFile();
        // 如果saveGeneratedFiles為true 則生成字節(jié)碼文件,所以在開始我們要設(shè)置這個參數(shù)
        // 當(dāng)然,也可以通過返回的bytes自己輸出
        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:為所有方法生成代理調(diào)度代碼,將代理方法對象集合起來。
         */
        //增加 hashcode、equals、toString方法
        addProxyMethod(hashCodeMethod, Object.class);
        addProxyMethod(equalsMethod, Object.class);
        addProxyMethod(toStringMethod, Object.class);
        // 獲得所有接口中的所有方法,并將方法添加到代理方法中
        for (Class<?> intf : interfaces) {
            for (Method m : intf.getMethods()) {
                addProxyMethod(m, intf);
            }
        }
 
        /*
         * 驗證方法簽名相同的一組方法,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值一樣
         */
        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 {
            // 生成代理類的構(gòu)造函數(shù)
            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());
                }
            }
            // 為代理類生成靜態(tài)代碼塊,對一些字段進行初始化
            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.
         * 設(shè)置只讀,在這之前不允許在常量池中增加信息,因為要寫常量池表
         */
        cp.setReadOnly();
 
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);
 
        try {
            // u4 magic;
            dout.writeInt(0xCAFEBABE);
            // u2 次要版本;
            dout.writeShort(CLASSFILE_MINOR_VERSION);
            // u2 主版本
            dout.writeShort(CLASSFILE_MAJOR_VERSION);
 
            cp.write(dout);             // (write constant pool)
 
            // u2 訪問標(biāo)識;
            dout.writeShort(accessFlags);
            // u2 本類名;
            dout.writeShort(cp.getClass(dotToSlash(className)));
            // u2 父類名;
            dout.writeShort(cp.getClass(superclassName));
            // u2 接口;
            dout.writeShort(interfaces.length);
            // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass(
                        dotToSlash(intf.getName())));
            }
            // u2 字段;
            dout.writeShort(fields.size());
            // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout);
            }
            // u2 方法;
            dout.writeShort(methods.size());
            // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout);
            }
            // u2 類文件屬性:對于代理類來說沒有類文件屬性;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes)
 
        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }
 
        return bout.toByteArray();
    }

通過addProxyMethod()添加hashcode、equals、toString方法。

private void addProxyMethod(Method var1, Class var2) {
        String var3 = var1.getName();  //方法名
        Class[] var4 = var1.getParameterTypes();   //方法參數(shù)類型數(shù)組
        Class var5 = var1.getReturnType();    //返回值類型
        Class[] var6 = var1.getExceptionTypes();   //異常類型
        String var7 = var3 + getParameterDescriptors(var4);   //方法簽名
        Object var8 = (List)this.proxyMethods.get(var7);   //根據(jù)方法簽名卻獲得proxyMethods的Value
        if(var8 != null) {    //處理多個代理接口中重復(fù)的方法的情況
            Iterator var9 = ((List)var8).iterator();
            while(var9.hasNext()) {
                ProxyGenerator.ProxyMethod var10 = (ProxyGenerator.ProxyMethod)var9.next();
                if(var5 == var10.returnType) {
                    /*歸約異常類型以至于讓重寫的方法拋出合適的異常類型,我認(rèn)為這里可能是多個接口中有相同的方法,而這些相同的方法拋出的異常類                      型又不同,所以對這些相同方法拋出的異常進行了歸約*/
                    ArrayList var11 = new ArrayList();
                    collectCompatibleTypes(var6, var10.exceptionTypes, var11);
                    collectCompatibleTypes(var10.exceptionTypes, var6, var11);
                    var10.exceptionTypes = new Class[var11.size()];
                    //將ArrayList轉(zhuǎn)換為Class對象數(shù)組
                    var10.exceptionTypes = (Class[])var11.toArray(var10.exceptionTypes);
                    return;
                }
            }
        } else {
            var8 = new ArrayList(3);
            this.proxyMethods.put(var7, var8);
        }    
        ((List)var8).add(new ProxyGenerator.ProxyMethod(var3, var4, var5, var6, var2, null));
       /*如果var8為空,就創(chuàng)建一個數(shù)組,并以方法簽名為key,proxymethod對象數(shù)組為value添加到proxyMethods*/
    }

生成的代理對象$Proxy0.class字節(jié)碼反編譯:

package com.sun.proxy;
 
import com.jpeony.spring.proxy.jdk.IHello;
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 IHello // 繼承了Proxy類和實現(xiàn)IHello接口
{
  // 變量,都是private static Method  XXX
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m0;
 
  // 代理類的構(gòu)造函數(shù),其參數(shù)正是是InvocationHandler實例,Proxy.newInstance方法就是通過通過這個構(gòu)造函數(shù)來創(chuàng)建代理實例的
  public $Proxy0(InvocationHandler paramInvocationHandler)
    throws 
  {
    super(paramInvocationHandler);
  }
 
  // 以下Object中的三個方法
  public final boolean equals(Object paramObject)
    throws 
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  // 接口代理方法
  public final void sayHello()
    throws 
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  public final String toString()
    throws 
  {
    try
    {
      return ((String)this.h.invoke(this, m2, null));
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  public final int hashCode()
    throws 
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
 
  // 靜態(tài)代碼塊對變量進行一些初始化工作
  static
  {
    try
    {
      // 這里每個方法對象 和類的實際方法綁定
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m3 = Class.forName("com.jpeony.spring.proxy.jdk.IHello").getMethod("sayHello", 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]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
      throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
    }
  }
}

當(dāng)代理對象生成后,最后由InvocationHandler的invoke()方法調(diào)用目標(biāo)方法:
在動態(tài)代理中InvocationHandler是核心,每個代理實例都具有一個關(guān)聯(lián)的調(diào)用處理程序(InvocationHandler)。
所以對代理方法的調(diào)用都是通InvocationHadler的invoke來實現(xiàn)中,而invoke方法根據(jù)傳入的代理對象,
方法和參數(shù)來決定調(diào)用代理的哪個方法。

方法簽名如下:

invoke(Object Proxy,Method method,Object[] args)

從反編譯源碼分析調(diào)用invoke()過程:

從反編譯后的源碼看$Proxy0類繼承了Proxy類,同時實現(xiàn)了IHello接口,即代理類接口,

所以才能強制將代理對象轉(zhuǎn)換為IHello接口,然后調(diào)用$Proxy0中的sayHello()方法。

$Proxy0中sayHello()源碼:

public final void sayHello()
    throws 
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

this.h.invoke(this, m3, null); this就是$Proxy0對象; m3就是m3 = Class.forName("com.jpeony.spring.proxy.jdk.IHello").getMethod("sayHello", new Class[0]);即是通過全路徑名,反射獲取的目標(biāo)對象中的真實方法加參數(shù)。
h就是Proxy類中的變量protected InvocationHandler h;

所以成功的調(diào)到了InvocationHandler中的invoke()方法,但是invoke()方法在我們自定義的MyInvocationHandler中實現(xiàn),MyInvocationHandler中的invoke()方法:

@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("------插入前置通知代碼-------------");
        // 執(zhí)行相應(yīng)的目標(biāo)方法
        Object rs = method.invoke(target,args);
        System.out.println("------插入后置處理代碼-------------");
        return rs;
    }

所以,繞了半天,終于調(diào)用到了MyInvocationHandler中的invoke()方法,從上面的this.h.invoke(this, m3, null);

可以看出,MyInvocationHandler中invoke第一個參數(shù)為$Proxy0(代理對象),第二個參數(shù)為目標(biāo)類的真實方法,第三個參數(shù)為目標(biāo)方法參數(shù),因為sayHello()沒有參數(shù),所以是null。

到這里,我們真正的實現(xiàn)了通過代理調(diào)用目標(biāo)對象的完全分析,至于InvocationHandler中的invoke()方法就是最后執(zhí)行了目標(biāo)方法。到此完成了代理對象生成,目標(biāo)方法調(diào)用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容