spring技術手冊上的一個java動態代理例子

火星人 @ 2014-03-09 , reply:0


  Java代碼

  public interface IHello {

  public void hello(String name);

  }

  Java代碼

  public class HelloImpl implements IHello{

  @Override

  public void hello(String name) {

  System.out.println("Hello:" name);

  }

  }

  Java代碼

  package proxy;

  import java.lang.reflect.InvocationHandler;

  import java.lang.reflect.Method;

  import java.lang.reflect.Proxy;

  import org.apache.log4j.Level;

  import org.apache.log4j.Logger;

  public class LogHandler implements InvocationHandler {

  private Logger logger = Logger.getLogger(this.getClass().getName());

  private Object delegate;

  public Object bind(Object delegate) {

  this.delegate = delegate;

  return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);

  }

  @Override

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

  Object result = null;

  log("method starts..." method);

  result = method.invoke(delegate, args);

  logger.log(Level.INFO,"methods ends ..." method);

  return result;

  }

  private void log(String message) {

  logger.log(Level.INFO,message);

  }

  public static void main(String[] args) {

  LogHandler logHandler = new LogHandler();

  IHello helloProxy = (IHello)logHandler.bind(new HelloImpl());

  helloProxy.hello("ssssssssssssss");

  }

  }





[火星人 via ] spring技術手冊上的一個java動態代理例子已經有220次圍觀

http://www.coctec.com/docs/java/show-post-60134.html