ITPub博客

首页 > IT职业 > IT图书 > guava反射:Reflection.newProxy方法简化动态代理

guava反射:Reflection.newProxy方法简化动态代理

IT图书 作者:firefule 时间:2021-09-09 09:39:17 0 删除 编辑

原理上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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1834/viewspace-2805651/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 数据库视图介绍
请登录后发表评论 登录
全部评论

注册时间:2019-07-24

  • 博文量
    105
  • 访问量
    15347