原理上Google Guava的动态代理也是使用JDK的动态代理,这是做了封装,更加简便。另外一点是能够很好的检查需要代理的对象必须拥有接口。使用Class类的isInterface()
来做检查。
下面我们先比较一下jdk动态代理和guava动态代理的实现:
JDK动态代理:
Foo foo = (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader(), new Class<?>[] {Foo.class}, invocationHandler);
Guava动态代理:
Foo foo = Reflection.newProxy(Foo.class, invocationHandler);
可以看出使用Guava的方式更简洁一些,下面我们用一个具体的例子来看下:
package cn.outofmemory.guava.reflect; import com.google.common.reflect.Reflection; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by outofmemory.cn on 2014/7/31. */ public class DynamicProxyDemo { public static void main(String[] args) { InvocationHandler invocationHandler = new MyInvocationHandler(); // Guava Dynamic Proxy implement IFoo foo = Reflection.newProxy(IFoo.class, invocationHandler); foo.doSomething(); //jdk Dynamic proxy implement IFoo jdkFoo = (IFoo) Proxy.newProxyInstance( IFoo.class.getClassLoader(), new Class<?>[]{IFoo.class}, invocationHandler); jdkFoo.doSomething(); } public static class MyInvocationHandler implements InvocationHandler{ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("proxy println something"); return null; } } public static interface IFoo { void doSomething(); } }
就是这样了,非常简单。
原文链接:http://outofmemory.cn/java/guava/reflect/Reflection-simplify-Dynamic-proxy
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦