Vincent

          Vicent's blog
          隨筆 - 74, 文章 - 0, 評論 - 5, 引用 - 0
          數據加載中……

          InvocationHandler 操作例子(切面概念)

          三個類,一個接口,不費話:


          程序代碼 程序代碼



          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");
          }



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

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

          主站蜘蛛池模板: 大洼县| 肥城市| 轮台县| 运城市| 西乌珠穆沁旗| 迁安市| 岚皋县| 新巴尔虎左旗| 鄄城县| 密云县| 上杭县| 隆德县| 微博| 栖霞市| 大埔县| 潜江市| 嘉黎县| 海南省| 喀喇| 石棉县| 永寿县| 县级市| 黑水县| 加查县| 苏尼特左旗| 安图县| 科技| 昂仁县| 太湖县| 元谋县| 桐柏县| 本溪市| 卢氏县| 廉江市| 辽源市| 漯河市| 城口县| 五原县| 济宁市| 定南县| 理塘县|