日期:2014-05-20  浏览次数:20695 次

interface.class
import static net.mindview.util.Print.*;

interface Interface {
  void doSomething();
  void somethingElse(String arg);
}

class RealObject implements Interface {
  public void doSomething() { print("doSomething"); }
  public void somethingElse(String arg) {
  print("somethingElse " + arg);
  }
}

class SimpleProxy implements Interface {
  private Interface proxied;
  public SimpleProxy(Interface proxied) {
  this.proxied = proxied;
  }
  public void doSomething() {
  print("SimpleProxy doSomething");
  proxied.doSomething();
  }
  public void somethingElse(String arg) {
  print("SimpleProxy somethingElse " + arg);
  proxied.somethingElse(arg);
  }
}

class SimpleProxyDemo {
  public static void consumer(Interface iface) {
  iface.doSomething();
  iface.somethingElse("bonobo");
  }
  public static void main(String[] args) {
  consumer(new RealObject());
  consumer(new SimpleProxy(new RealObject()));
  }
} /* Output:
doSomething
somethingElse bonobo
SimpleProxy doSomething
doSomething
SimpleProxy somethingElse bonobo
somethingElse bonobo
*///:~


import java.lang.reflect.*;

class DynamicProxyHandler implements InvocationHandler {
  private Object proxied;
  public DynamicProxyHandler(Object proxied) {
  this.proxied = proxied;
  }
  public Object
  invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
  System.out.println("**** proxy: " + proxy.getClass() +
  ", method: " + method + ", args: " + args);
  if(args != null)
  for(Object arg : args)
  System.out.println(" " + arg);
  return method.invoke(proxied, args);
  }
}

class SimpleDynamicProxy {
  public static void consumer(Interface iface) {
  iface.doSomething();
  iface.somethingElse("bonobo");
  }
  public static void main(String[] args) {
  RealObject real = new RealObject();
  consumer(real);
  // Insert a proxy and call again:
  Interface proxy = (Interface)Proxy.newProxyInstance(
  Interface.class.getClassLoader(),
  new Class[]{ Interface.class },
  new DynamicProxyHandler(real));
  consumer(proxy);
  }
} /* Output: (95% match)
doSomething
somethingElse bonobo
**** proxy: class $Proxy0, method: public abstract void Interface.doSomething(), args: null
doSomething
**** proxy: class $Proxy0, method: public abstract void Interface.somethingElse(java.lang.String), args: [Ljava.lang.Object;@42e816
  bonobo
somethingElse bonobo
*///:~


请问 Interface proxy = (Interface)Proxy.newProxyInstance(
  Interface.class.getClassLoader(),
  new Class[]{ Interface.class },
  new DynamicProxyHandler(real));
  consumer(proxy);
  }
这里怎么会用Interface.class.getClassLoader(),
Interface是接口,为何可以用.class
还有就是这个Proxy.newProxyInstance用法

------解决方案--------------------
Interface.class对应Interface这个类装载后的信息
Proxy.newProxyInstance看这里
http://www.ticmy.com/?p=200
------解决方案--------------------
这个只是动态代理的写法而已,第一个参数是需要一个classloader,只是这里用的是Interface的classloader而已,具体的你还是自己去好好看看动态代理部分的东西吧。