Vincent

          Vicent's blog
          隨筆 - 74, 文章 - 0, 評(píng)論 - 5, 引用 - 0
          數(shù)據(jù)加載中……

          InvocationHandler 操作例子(切面概念)

          三個(gè)類,一個(gè)接口,不費(fèi)話:


          程序代碼 程序代碼



          public interface IHello {
          public void hello(String name);
          }



          --------------------------------------------------------------------------------
          public class HelloSpeaker implements IHello {


          public void hello(String name) {
          System.out.println("Hello, " + name);
          }

          }


          --------------------------------------------------------------------------------
          import java.lang.reflect.InvocationHandler;
          import java.lang.reflect.Method;
          import java.lang.reflect.Proxy;
          import java.util.logging.Level;
          import java.util.logging.Logger;

          public class LogHandler implements InvocationHandler {
          private Object delegate;

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

          public Object bind(Object delegate) {
          this.delegate = delegate;
          return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this);
          }

          public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
          Object result = null;

          try {
          log("method starts..." + method);

          result = method.invoke(delegate, args);

          logger.log(Level.INFO, "method ends..." + method);
          } catch (Exception e) {
          log(e.toString());
          }

          return result;
          }

          private void log(String message) {
          logger.log(Level.INFO, message);
          }
          }


          --------------------------------------------------------------------------------


          public class ProxyDemo {

          public static void main(String[] args) {
          LogHandler logHandler = new LogHandler();

          IHello helloProxy = (IHello) logHandler.bind(new HelloSpeaker());
          helloProxy.hello("Justin");
          }



          好了,拷貝上面的自己運(yùn)行看看就知道了,原來切面就是這么回事。

          posted on 2006-08-22 10:43 Binary 閱讀(208) 評(píng)論(0)  編輯  收藏 所屬分類: j2se

          主站蜘蛛池模板: 清涧县| 西华县| 沙田区| 星座| 沅陵县| 临西县| 富阳市| 运城市| 夏津县| 台山市| 哈密市| 沾益县| 荔波县| 盐源县| 安远县| 石首市| 东光县| 手机| 台前县| 厦门市| 南开区| 苏尼特右旗| 白银市| 罗定市| 平湖市| 高陵县| 明光市| 昌都县| 江都市| 于田县| 怀来县| 夏邑县| 津市市| 德令哈市| 逊克县| 广宁县| 桓台县| 琼海市| 兴业县| 沙洋县| 长葛市|