疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java动态代理


 

    1、接口

  public interface Foo {

  void modify();

  void ff(int x);

  }

  2、被代理类

  public class FooImpl implements Foo {

 

  public void modify() {

  System.out.println("*******modify()方法被调用");

  }

  

  public void ff(int x) {

  System.out.println("ff()方法被调用啦啊啊啊啊啊啊啊");

  }

  }

  3、动态代理类

  import java.lang.reflect.InvocationHandler;

  import java.lang.reflect.Method;

  public class MyInvocationHandler implements InvocationHandler {

  private Object o=null;

  public MyInvocationHandler(Object o){

  this.o=o;

  }

  public Object invoke(Object proxy, Method method, Object[] args)

  throws Throwable {

  System.out.println(method.getName()+"被调用,参数:"+args[0].toString());

  Object ret = method.invoke(this.o, args);

  System.out.println(method.getName()+"调用结束");

  return ret;

  }

  }

  4、测试程序及结果

  import java.lang.reflect.InvocationHandler;

  import java.lang.reflect.InvocationTargetException;

  import java.lang.reflect.Proxy;

  public class ProxyClass {

  public static void main(String arags[]) throws IllegalArgumentException,

  SecurityException, InstantiationException, IllegalAccessException,

  InvocationTargetException, NoSuchMethodException {

  InvocationHandler handler = new MyInvocationHandler(new FooImpl());

  Class proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(),

  new Class[] { Foo.class });

  Foo f = (Foo) proxyClass.getConstructor(

  new Class[] { InvocationHandler.class }).newInstance(

  new Object[] { handler });

  //f.modify();

  f.ff(2211);

  }

  }

  ff被调用,参数2211

  ff()方法被调用啦啊啊啊啊啊啊啊

  ff调用结束