熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

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

2022-06-13   來源: Java開源技術 

  Java代碼

  public interface IHello {

  public void hello(String name);

  }

  Java代碼

  public class HelloImpl implements IHello{

  @Override

  public void hello(String name) {

  Systemoutprintln(Hello: + name);

  }

  }

  Java代碼

  package proxy;

  import javalangreflectInvocationHandler;

  import javalangreflectMethod;

  import javalangreflectProxy;

  import orgapachelogjLevel;

  import orgapachelogjLogger;

  public class LogHandler implements InvocationHandler {

  private Logger logger = LoggergetLogger(thisgetClass()getName());

  private Object delegate;

  public Object bind(Object delegate) {

  thisdelegate = delegate;

  return ProxynewProxyInstance(delegategetClass()getClassLoader() delegategetClass()getInterfaces() this);

  }

  @Override

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

  Object result = null;

  log(method starts + method);

  result = methodinvoke(delegate args);

  loggerlog(LevelINFOmethods ends + method);

  return result;

  }

  private void log(String message) {

  loggerlog(LevelINFOmessage);

  }

  public static void main(String[] args) {

  LogHandler logHandler = new LogHandler();

  IHello helloProxy = (IHello)logHandlerbind(new HelloImpl());

  helloProxyhello(ssssssssssssss);

  }

  }


From:http://tw.wingwit.com/Article/program/Java/ky/201311/28578.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.