随笔-16  评论-50  文章-2  trackbacks-0

如果想在运行时生成新的对象,并且这个对象的类型是全新的,是现有系统中没有的。就可以用Proxy类中的静态方法newProxyInstance来实现。其API如下:

public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler handler);

参数:

  • loader: 类加载器。如果为null,就要默认类加载器
  • interfaces: 这个新类要实现的接口组
  • 调用处理器。

函数返回的对象类型是$Proxyn, (n >= 0. 第一次调用这个方法,新类名为$Proxy0, 第二个新类名为$Proxy1, 以此类推)

生成的$Proxyn 的源代码大致类似如此:

public final class $Proxy0 implements interfaces {
    InvocationHandler handler;

    public String toString() {
        Method m = this.getClass().getMethod("toString");
        handler.invoke(this, m, m.getParameters());
    }

    public int hashCode() {
        Method m = this.getClass().getMethod("hashCode");
        handler.invoke(this, m, m.getParameters());
    }

    public String equals() {
        Method m = this.getClass().getMethod("equals");
        handler.invoke(this, m, m.getParameters());
    }

   
    // 以下是实现interfaces的方法
    public return_type interfaces_method(args...) {
        Method m = this.getClass().getMethod("equals");
        handler.invoke(this, m, m.getParameters());       
   }

   ... ...接口interfaces中的其他方法  
}

 

当我们这样调用时: Object o = Proxy.newProxyInstance(null, interfaces, handler0);

就生成一个新$Proxy0类的对象o, 这个对象o的字段handler被赋值为handler0。$Proxy0实现了interfaces中所有的接口,其实现方式都一样,就是调用字段handler的invoke方法。其UML图如下:

proxy

posted on 2008-01-06 14:11 Jeff Lau 阅读(1463) 评论(1)  编辑  收藏 所属分类: Jeff On Java 2008

评论:
# re: 代理(Proxy) 2008-02-29 10:08 | CoderDream
不错!

不过都是伪代码,让初学者很难看懂!  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: