java動(dòng)態(tài)代理作用及源碼分析

一、理解

  • 靜態(tài)代理:靜態(tài)代理是在編譯時(shí)就將接口、實(shí)現(xiàn)類、代理類一股腦兒全部手動(dòng)完成
  • 動(dòng)態(tài)代理:在程序運(yùn)行期間根據(jù)需要?jiǎng)討B(tài)的創(chuàng)建代理類及其實(shí)例坟漱,來完成具體的功能

二、應(yīng)用場景

  • 參考裝飾器模式更哄,在已有的方法中進(jìn)行再次封裝芋齿,實(shí)現(xiàn)新增功能
  • AOP面向切面編程思想

三、實(shí)現(xiàn)代碼

在了解了動(dòng)態(tài)代理之前成翩,我們先通過最簡單的例子看靜態(tài)代理是如何實(shí)現(xiàn)的觅捆。
先定義一個(gè)接口

package about_proxy.static_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public interface Subject {

    public void doSomething();

}

完成一個(gè)該接口的實(shí)現(xiàn)類,并實(shí)現(xiàn)doSomething方法

package about_proxy.static_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class RealSubject implements Subject {

    @Override
    public void doSomething() {

        System.out.println("call doSomething()");

    }
}

假如這時(shí)有需求麻敌,需要改寫doSomething方法栅炒,再方法執(zhí)行前后增加日志打印功能,并計(jì)算該功能耗時(shí),可是其中實(shí)現(xiàn)邏輯復(fù)雜<貌似并不復(fù)雜赢赊,只有一句打印乙漓,不要在意這些細(xì)節(jié)。>释移,不想修改原有代碼叭披,這時(shí)我們新建一個(gè)代理類,在其中實(shí)現(xiàn)我們需要的功能玩讳。

package about_proxy.static_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class SubjectProxy implements Subject {

    Subject subimpl = new RealSubject();

    @Override
    public void doSomething() {
        System.out.println("我們先做點(diǎn)什么");
        subimpl.doSomething();
        System.out.println("我們?cè)僮鳇c(diǎn)什么");

    }
}

這個(gè)時(shí)候我們就可以利用新的代理類來實(shí)現(xiàn)新的需求涩蜘,而不用修改源代碼。下面完成測試類

package about_proxy.static_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class TestStaticProxy {

    public static void main(String args[]) {
//        Subject sub = new RealSubject();
        Subject sub = new SubjectProxy();
        sub.doSomething();
    }
}

好啦熏纯,這時(shí)候我們已經(jīng)完成了需求人員的要求了同诫。可是這個(gè)時(shí)候豆巨,老板又跳出來剩辟,說我想測試一下工程中多個(gè)類中方法的耗時(shí)掐场。
干往扔!我要新建多少個(gè)代理類啊。
這個(gè)時(shí)候動(dòng)態(tài)代理就應(yīng)運(yùn)而生了熊户。首先我們還是定義接口

package about_proxy.dynamic_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public interface Subject {
    public void doSomething();
}

然后定義實(shí)現(xiàn)類

package about_proxy.dynamic_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class RealSubject implements Subject {
    @Override
    public void doSomething() {
        System.out.println("call doSomething()");
    }
}

上面我們就完成了準(zhǔn)備工作萍膛,接下來實(shí)現(xiàn)動(dòng)態(tài)代理

package about_proxy.dynamic_proxy;

import org.omg.CORBA.portable.InvokeHandler;
import sun.rmi.runtime.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class ProxyHandler implements InvocationHandler {

    private Object tar;


    public Object bind(Object tar)
    {
        this.tar = tar;
        //綁定該類實(shí)現(xiàn)的所有接口,取得代理類
        return Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);
    }



    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object result = null;
        //這里就可以進(jìn)行所謂的AOP編程了
        //在調(diào)用具體函數(shù)方法前嚷堡,執(zhí)行功能處理
        System.out.println("start time:"+System.currentTimeMillis());
        result = method.invoke(tar,args);
        //在調(diào)用具體函數(shù)方法后蝗罗,執(zhí)行功能處理
        System.out.println("end time:"+System.currentTimeMillis());
        return result;

    }
}

最后再測試類中使用動(dòng)態(tài)代理

package about_proxy.dynamic_proxy;

/**
 * Created by solie_h on 2018/2/7.
 */
public class TestDynamicProxy {

    public static void main(String args[]){
//        Subject sub = new RealSubject();
        ProxyHandler proxy = new ProxyHandler();
        //綁定該類實(shí)現(xiàn)的所有接口
        Subject sub = (Subject) proxy.bind(new RealSubject());
        sub.doSomething();
    }
}

這樣我們就可以在一個(gè)ProxyHandler實(shí)現(xiàn)多個(gè)代理類的功能(本demo只使用了一個(gè)動(dòng)態(tài)代理),但是只創(chuàng)建了一個(gè)實(shí)體類蝌戒。是如何實(shí)現(xiàn)的呢串塑?動(dòng)態(tài)代理其實(shí)為我們?cè)谶\(yùn)行期間動(dòng)態(tài)生成了多個(gè)代理類,下面我們通過源碼來了解一下jdk中是如何操作的北苟。

四桩匪、原理簡析

我們可以debug一下demo,當(dāng)工程執(zhí)行到doSomething()方法時(shí)進(jìn)入了ProxyHandler類中的invoke方法友鼻,以實(shí)現(xiàn)了我們?cè)谡嬲膁oSomething()方法前后增加了自己想要的功能傻昙。
為什么會(huì)進(jìn)入invoke中呢?
在上述demo的main方法中調(diào)用了ProxyHandler的bind方法彩扔,

Subject sub = (Subject) proxy.bind(new RealSubject());

其實(shí)是調(diào)用了Proxy類的靜態(tài)方法newProxyInstance()

Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this);

這里便是生成代理的關(guān)鍵了妆档,我們繼續(xù)跟進(jìn)查看內(nèi)部關(guān)鍵

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

        /*
         * 獲取代理類。
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * 使用指定的invocationHandler調(diào)用構(gòu)造方法
         */
        try {
            if (sm != null) {
                checkNewProxyPermission(Reflection.getCallerClass(), cl);
            }
            //調(diào)用代理對(duì)象的構(gòu)造函數(shù)(代理對(duì)象的構(gòu)造函數(shù)$Proxy0(InvocationHandler h)虫碉,通過字節(jié)碼反編譯可以查看生成的代理類)  
            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;
                    }
                });
            }
            //生成代理類的實(shí)例贾惦,并把MyInvocationHander的實(shí)例作為構(gòu)造函數(shù)參數(shù)傳入  
            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);
        }
    }

我們繼續(xù)看是如何獲取代理類的,跟入Class<?> cl = getProxyClass0(loader, intfs)方法

   /**
    * Generate a proxy class.  Must call the checkProxyAccess method
    * to perform permission checks before calling this.
    */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        //實(shí)現(xiàn)接口的最大數(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
        //調(diào)用了get方法
        return proxyClassCache.get(loader, interfaces);
    }

繼續(xù)跟入proxyClassCache.get(loader, interfaces);

    /**
     * @param key       上面?zhèn)魅氲膌oader,類加載器
     * @param parameter 上面方法傳入的interfaces纤虽,接口數(shù)組
     */
    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
                // 返回的value是通過該方法調(diào)用的
                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);
                }
            }
        }
    }

我們繼續(xù)查看supplier.get()方法乳绕,該方法的實(shí)現(xiàn)在WeakCache的內(nèi)部類Factory中,代碼如下

        @Override
        public synchronized V get() { // serialize access
            // re-check
            Supplier<V> 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.apply(key, parameter)得到value進(jìn)行返回
                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;

            // wrap value with CacheValue (WeakReference)
            CacheValue<V> cacheValue = new CacheValue<>(value);

            // try replacing us with CacheValue (this should always succeed)
            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;
        }
    }

繼續(xù)跟蹤valueFactory.apply(key, parameter)方法逼纸,該方法的實(shí)現(xiàn)在Proxy的內(nèi)部類ProxyClassFactory中

@Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            for (Class<?> intf : interfaces) {
                /*
                 * 確保該loader加載的此類(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");
                }
                /*
                 * 確保是一個(gè)接口
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * 確保接口沒重復(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;

            /*
             * 驗(yàn)證所有非公共的接口在同一個(gè)包內(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
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * 為代理類生成一個(gè)名字,防止重復(fù)
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * 具體生成代理類的方法又在該方法中實(shí)現(xiàn)
             */
            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(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è)置這個(gè)參數(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;
    }

繼續(xù)跟生成自己碼的代碼,這里便是最終的生成方法了

private byte[] generateClassFile() {
  /* ============================================================
   * Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
   * 步驟1:為所有方法生成代理調(diào)度代碼贺嫂,將代理方法對(duì)象集合起來滓鸠。
   */
  //增加 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);
   }
  }

  /*
   * 驗(yàn)證方法簽名相同的一組方法糜俗,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值一樣
   */
  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)造方法
   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.
   * 在開始編寫最終類文件之前曲饱,確保為下面的項(xiàng)目保留常量池索引悠抹。
   */
  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è)置只讀,在這之前不允許在常量池中增加信息扩淀,因?yàn)橐獙懗A砍乇?   */
  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)識(shí);
   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 類文件屬性:對(duì)于代理類來說沒有類文件屬性;
   dout.writeShort(0); // (no ClassFile attributes for proxy classes)

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

  return bout.toByteArray();
 }

上面對(duì)源碼一頓分析楔敌,接下來我們將demo中調(diào)用bind方法中Proxy.newProxyInstance(tar.getClass().getClassLoader(), tar.getClass().getInterfaces(), this)動(dòng)態(tài)生成的代理類打印出來,修改我們的demo

package about_proxy.dynamic_proxy;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by solie_h on 2018/2/7.
 */
public class TestDynamicProxy {

    public static void main(String args[]){
//        Subject sub = new RealSubject();
        ProxyHandler proxy = new ProxyHandler();
        //綁定該類實(shí)現(xiàn)的所有接口
        Subject sub = (Subject) proxy.bind(new RealSubject());
        // 將動(dòng)態(tài)生成的代理類打印出來
        // 這里需要修改為你需要輸出的路徑
        String path = "請(qǐng)修改路徑/TestProxy.class";
        byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy0",RealSubject.class.getInterfaces());
        FileOutputStream out = null;

        try {
            out = new FileOutputStream(path);
            out.write(classFile);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sub.doSomething();

    }

}

將生成的TestProxy.class文件反編譯驻谆,這里給不熟悉反編譯操作的同學(xué)提供一個(gè)在線反編譯工具:http://www.javadecompilers.com/

import about_proxy.dynamic_proxy.Subject;
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 Subject
{
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m0;
  
  public $Proxy0(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }
  
  public final boolean equals(Object paramObject)
  {
    try
    {
      return ((Boolean)h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final void doSomething()
  {
    try
    {
      h.invoke(this, m3, null);
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final String toString()
  {
    try
    {
      return (String)h.invoke(this, m2, null);
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final int hashCode()
  {
    try
    {
      return ((Integer)h.invoke(this, m0, null)).intValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", 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());
    }
  }
}

我們先來看該類的構(gòu)造方法

 public $Proxy0(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }

傳入?yún)?shù)為InvocationHandler卵凑,這就是為什么動(dòng)態(tài)代理類在調(diào)用接口中方法時(shí)會(huì)走到自定義的InvocationHandler中的invoke方法。
super(paramInvocationHandler)胜臊,是調(diào)用父類Proxy的構(gòu)造方法勺卢。而父類又持有protected InvocationHandler h的實(shí)例,參考Proxy的構(gòu)造方法:

  protected Proxy(InvocationHandler h) {
        Objects.requireNonNull(h);
        this.h = h;
    }

在繼續(xù)看反編譯出來文件的靜態(tài)代碼塊

static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m3 = Class.forName("about_proxy.dynamic_proxy.Subject").getMethod("doSomething", 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());
    }
  }

我們?cè)诮涌谥卸x的方法doSomething通過反射得到的名字是m3象对,我們繼續(xù)查看文件中實(shí)現(xiàn)的doSomething()方法

  public final void doSomething()
  {
    try
    {
      h.invoke(this, m3, null);
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }

這里調(diào)用代理對(duì)象的doSomething方法黑忱,直接就調(diào)用了InvocationHandler中的invoke方法,并把m3傳了進(jìn)去织盼。
this.h.invoke(this, m3, null);
其余的equals杨何、toString、hashCode也是同樣的道理沥邻。
到這里就很明了了危虱,所有的動(dòng)態(tài)代理流程也清晰了。

五唐全、總結(jié)

JDK是動(dòng)態(tài)生成代理類埃跷,并通過調(diào)用解析器蕊玷,執(zhí)行接口實(shí)現(xiàn)的方法的原理已經(jīng)一目了然。動(dòng)態(tài)代理加上反射弥雹,是很多框架的基礎(chǔ)垃帅。期待下一章節(jié)實(shí)現(xiàn)根據(jù)動(dòng)態(tài)代理與反射實(shí)現(xiàn)的android的注入框架原理解析。

個(gè)人見解剪勿,若有錯(cuò)誤之處贸诚,歡迎指出更正

文章中demo放置在github
https://github.com/loosaSH/java-Proxy

參考文章:
1、Java帝國之動(dòng)態(tài)代理(用故事形式講解動(dòng)態(tài)代理的出現(xiàn)及原理)
2厕吉、知乎-Java 動(dòng)態(tài)代理作用是什么酱固?
3、簡書-動(dòng)態(tài)代理
4头朱、JDK8動(dòng)態(tài)代理源碼分析

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末运悲,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子项钮,更是在濱河造成了極大的恐慌班眯,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件烁巫,死亡現(xiàn)場離奇詭異署隘,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)程拭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門定踱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來棍潘,“玉大人恃鞋,你說我怎么就攤上這事∫嗲福” “怎么了恤浪?”我有些...
    開封第一講書人閱讀 164,298評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長肴楷。 經(jīng)常有香客問我水由,道長,這世上最難降的妖魔是什么赛蔫? 我笑而不...
    開封第一講書人閱讀 58,586評(píng)論 1 293
  • 正文 為了忘掉前任砂客,我火速辦了婚禮,結(jié)果婚禮上呵恢,老公的妹妹穿的比我還像新娘鞠值。我一直安慰自己,他們只是感情好渗钉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評(píng)論 6 392
  • 文/花漫 我一把揭開白布彤恶。 她就那樣靜靜地躺著钞钙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪声离。 梳的紋絲不亂的頭發(fā)上芒炼,一...
    開封第一講書人閱讀 51,488評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音术徊,去河邊找鬼本刽。 笑死,一個(gè)胖子當(dāng)著我的面吹牛赠涮,可吹牛的內(nèi)容都是我干的盅安。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼世囊,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼别瞭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起株憾,我...
    開封第一講書人閱讀 39,176評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤蝙寨,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后嗤瞎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體墙歪,經(jīng)...
    沈念sama閱讀 45,619評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評(píng)論 3 336
  • 正文 我和宋清朗相戀三年贝奇,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了虹菲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡掉瞳,死狀恐怖毕源,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情陕习,我是刑警寧澤霎褐,帶...
    沈念sama閱讀 35,655評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站该镣,受9級(jí)特大地震影響冻璃,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜损合,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評(píng)論 3 329
  • 文/蒙蒙 一省艳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧嫁审,春花似錦跋炕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽嬉探。三九已至,卻和暖如春棉圈,著一層夾襖步出監(jiān)牢的瞬間涩堤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評(píng)論 1 269
  • 我被黑心中介騙來泰國打工分瘾, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留耸黑,地道東北人斗蒋。 一個(gè)月前我還...
    沈念sama閱讀 48,095評(píng)論 3 370
  • 正文 我出身青樓韭畸,卻偏偏與公主長得像喻犁,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子上岗,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評(píng)論 2 354