创建代理类实例的三种方法

来源:互联网 发布:python游戏开发平台 编辑:程序博客网 时间:2024/06/05 19:58

  • 第一种:
Class clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);//得到其有参的构造方法Constructor con=clazzProxy.getConstructor(InvocationHandler.class);//创建一个内部类,该类为上面所得方法的的参数类class MyInvocationHandler implements InvocationHandler{@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stubreturn null;}}con.newInstance(new MyInvocationHandler());


  • 第二种
//获得Collection代理类Class clazzProxy=Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);//把参数定义成匿名内部类con.newInstance(new InvocationHandler(){@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stubreturn null;}});


  • 第三种
//第三中获得代理类实例的方法---直接用Proxy类的静态方法,来获得其代理类的实例Collection proxy=(Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),new Class[]{Collection.class},new InvocationHandler(){ArrayList target=new ArrayList();@Overridepublic Object invoke(Object proxy, Method method,Object[] args) throws Throwable {// TODO Auto-generated method stubObject obj=method.invoke(target, args);return obj;}});


0 0