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 閱讀(209) 評(píng)論(0)  編輯  收藏 所屬分類: j2se

          主站蜘蛛池模板: 大冶市| 阆中市| 温宿县| 错那县| 江源县| 古蔺县| 格尔木市| 通州区| 华安县| 安龙县| 伊宁市| 精河县| 安塞县| 阜平县| 古浪县| 宜都市| 樟树市| 沽源县| 宣威市| 瑞金市| 准格尔旗| 昌图县| 阳山县| 涞源县| 保靖县| 张北县| 郁南县| 镇沅| 眉山市| 鞍山市| 龙门县| 库车县| 家居| 韶山市| 万宁市| 清镇市| 洛扎县| 措勤县| 南宁市| 平远县| 济阳县|