Spring-jdk代理-原理

上簡單小例子:

接口
public interface IHello {

    public void sayHello(String str);

}
目標(biāo)對(duì)象
public class Hello implements IHello{

    @Override
    public void sayHello(String str) {
        System.out.println("hello:"+str);
    }
}
代理類
public class DynaProxyHello implements InvocationHandler {

        //目標(biāo)對(duì)象
        private Object target;

        /**
         * 將被代理對(duì)象塞入,獲取代理類
         * @param object
         * @return
         */
        public Object bind(Object object){
            this.target = object;
            return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object result = null;
            //通過反射機(jī)制來運(yùn)行目標(biāo)對(duì)象的方法
            result = method.invoke(this.target, args);
            return result;
        }

}

此處有兩個(gè)疑問:1.Proxy.newProxyInstance()如何實(shí)現(xiàn)的代理逸绎、2.InvocationHandler接口的invoke()方法何時(shí)被調(diào)用学辱,作用是什么耀里?

1.jdk代理如何實(shí)現(xiàn)的?

通過代碼:Proxy.newProxyInstance()發(fā)現(xiàn)

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

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         * Look up or generate the designated proxy class.
         */
        Class<?> cl = getProxyClass0(loader, intfs);

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

            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (!Modifier.isPublic(cl.getModifiers())) {
                AccessController.doPrivileged(new PrivilegedAction<Void>() {
                    public Void run() {
                        cons.setAccessible(true);
                        return null;
                    }
                });
            }
            return cons.newInstance(new Object[]{h});
        } catch (IllegalAccessException|InstantiationException e) {
            throw new InternalError(e.toString(), e);
        } catch (InvocationTargetException e) {
            Throwable t = e.getCause();
            if (t instanceof RuntimeException) {
                throw (RuntimeException) t;
            } else {
                throw new InternalError(t.toString(), t);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString(), e);
        }
    }

其中: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) {
        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);
                }
            }
        }
    }

其中:subKeyFactory.apply(key, parameter)

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
            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
                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.
             */
            // 這里是真正生成代理類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());
            }
        }
    }

這其中:byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);這里是真正生成代理類class字節(jié)碼的地方(類似cglib)。
所以我們可以直接用這個(gè)方法 生成自己想要的代理類娱节。

public static byte[] generateProxyClass(final String var0, Class<?>[] var1, int var2) {
        ProxyGenerator var3 = new ProxyGenerator(var0, var1, var2);
        final byte[] var4 = var3.generateClassFile();
        // 此屬性表示是不是要產(chǎn)生代理類文件
        if(saveGeneratedFiles) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    try {
                        int var1 = var0.lastIndexOf(46);
                        Path var2;
                        if(var1 > 0) {
                            Path var3 = Paths.get(var0.substring(0, var1).replace('.', File.separatorChar), new String[0]);
                            Files.createDirectories(var3, new FileAttribute[0]);
                            var2 = var3.resolve(var0.substring(var1 + 1, var0.length()) + ".class");
                        } else {
                            var2 = Paths.get(var0 + ".class", new String[0]);
                        }

                        Files.write(var2, var4, new OpenOption[0]);
                        return null;
                    } catch (IOException var4x) {
                        throw new InternalError("I/O exception saving generated file: " + var4x);
                    }
                }
            });
        }

        return var4;
    }

其中:saveGeneratedFiles此屬性表示是不是要產(chǎn)生代理類文件

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

此值默認(rèn)jvm設(shè)置的是false,如果要修改默認(rèn)值:

System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

溫馨提示:產(chǎn)生的代理字節(jié)碼文件默認(rèn)存放位置是項(xiàng)目根目錄嫌蚤。
有了如上分析辐益,我們可以自己手動(dòng)創(chuàng)建指定對(duì)象的代理類字節(jié)碼文件。

public class TestMain {
    public static void main(String[] args) {

        createProxyClassFile();
        IHello a = new Hello();
        ProxyHelloSelfMake m = new ProxyHelloSelfMake(new DynaProxyHello(a));
        m.sayHello("lili");
    }

    private static void createProxyClassFile() {
        String name = "ProxyHelloSelfMake";
        byte[] data = ProxyGenerator.generateProxyClass(name, new Class[]{IHello.class});
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(name + ".class");
            System.out.println((new File("hello")).getAbsolutePath());
            out.write(data);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

運(yùn)行結(jié)果:


image.png

用jd-gui工具打開ProxyHelloSelfMake.class文件:

public final class ProxyHelloSelfMake
  extends Proxy
  implements IHello
{
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m0;
  
  public ProxyHelloSelfMake(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }
  
  public final boolean equals(Object paramObject)
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final void sayHello(String paramString)
  {
    try
    {
      this.h.invoke(this, m3, new Object[] { paramString });
      return;
    }
    catch (Error|RuntimeException localError)
    {
      throw localError;
    }
    catch (Throwable localThrowable)
    {
      throw new UndeclaredThrowableException(localThrowable);
    }
  }
  
  public final String toString()
  {
    try
    {
      return (String)this.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)this.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("com.jd.test.lfb.storage.IHello").getMethod("sayHello", new Class[] { Class.forName("java.lang.String") });
      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());
    }
  }
}

此文件的重點(diǎn)在于InvocationHandler的賦值

public ProxyHelloSelfMake(InvocationHandler paramInvocationHandler)
  {
    super(paramInvocationHandler);
  }

在創(chuàng)建ProxyHelloSelfMake時(shí)就要給他指定InvocationHandler脱吱,只有指定了InvocationHandler

 public final void sayHello(String paramString)
  {
    try
    {
      this.h.invoke(this, m3, new Object[] { paramString });
      return;
    }

this.h.invoke才知道反射哪個(gè)真正對(duì)象的m3方法智政。

此時(shí)說說第二個(gè)問題InvocationHandler接口的invoke()方法何時(shí)被調(diào)用,作用是什么箱蝠?

InvocationHandler是通過反射調(diào)用目標(biāo)方法续捂。

        @Override
        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            Object result = null;
            //通過反射機(jī)制來運(yùn)行目標(biāo)對(duì)象的方法
            result = method.invoke(this.target, args);
            return result;
        }

所以當(dāng)獲取到一個(gè)代理類后,進(jìn)行方法調(diào)用順序是這樣的:
開始--->proxyclass.method()--->字節(jié)碼中的method()--->實(shí)現(xiàn)了InvocationHandler接口中的invoke()--->反射調(diào)用method--->真實(shí)類的method方法--->結(jié)束
由此可見宦搬,
java.lang.reflect.InvocationHandler沒啥特別的只是起到了紐帶作用牙瓢,它銜接了目標(biāo)類和代理類。
也就是有了這個(gè)紐帶床三,方便了擴(kuò)展一罩。

client--proxy--target 關(guān)系圖:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市撇簿,隨后出現(xiàn)的幾起案子聂渊,更是在濱河造成了極大的恐慌,老刑警劉巖四瘫,帶你破解...
    沈念sama閱讀 222,807評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件汉嗽,死亡現(xiàn)場離奇詭異,居然都是意外死亡找蜜,警方通過查閱死者的電腦和手機(jī)饼暑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人弓叛,你說我怎么就攤上這事彰居。” “怎么了撰筷?”我有些...
    開封第一講書人閱讀 169,589評(píng)論 0 363
  • 文/不壞的土叔 我叫張陵陈惰,是天一觀的道長。 經(jīng)常有香客問我毕籽,道長抬闯,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,188評(píng)論 1 300
  • 正文 為了忘掉前任关筒,我火速辦了婚禮溶握,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蒸播。我一直安慰自己睡榆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,185評(píng)論 6 398
  • 文/花漫 我一把揭開白布廉赔。 她就那樣靜靜地躺著肉微,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蜡塌。 梳的紋絲不亂的頭發(fā)上碉纳,一...
    開封第一講書人閱讀 52,785評(píng)論 1 314
  • 那天,我揣著相機(jī)與錄音馏艾,去河邊找鬼劳曹。 笑死,一個(gè)胖子當(dāng)著我的面吹牛琅摩,可吹牛的內(nèi)容都是我干的铁孵。 我是一名探鬼主播,決...
    沈念sama閱讀 41,220評(píng)論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼房资,長吁一口氣:“原來是場噩夢啊……” “哼蜕劝!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起轰异,我...
    開封第一講書人閱讀 40,167評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤岖沛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后搭独,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體婴削,經(jīng)...
    沈念sama閱讀 46,698評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,767評(píng)論 3 343
  • 正文 我和宋清朗相戀三年牙肝,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了唉俗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嗤朴。...
    茶點(diǎn)故事閱讀 40,912評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖虫溜,靈堂內(nèi)的尸體忽然破棺而出雹姊,到底是詐尸還是另有隱情,我是刑警寧澤衡楞,帶...
    沈念sama閱讀 36,572評(píng)論 5 351
  • 正文 年R本政府宣布容为,位于F島的核電站,受9級(jí)特大地震影響寺酪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜替劈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,254評(píng)論 3 336
  • 文/蒙蒙 一寄雀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧陨献,春花似錦盒犹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至龄捡,卻和暖如春卓嫂,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背聘殖。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評(píng)論 1 274
  • 我被黑心中介騙來泰國打工晨雳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人奸腺。 一個(gè)月前我還...
    沈念sama閱讀 49,359評(píng)論 3 379
  • 正文 我出身青樓餐禁,卻偏偏與公主長得像,于是被迫代替她去往敵國和親突照。 傳聞我的和親對(duì)象是個(gè)殘疾皇子帮非,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,922評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容