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)行看看就知道了,原來(lái)切面就是這么回事。

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

          主站蜘蛛池模板: 张家界市| 留坝县| 沂南县| 腾冲县| 绿春县| 温泉县| 星座| 米泉市| 临西县| 玛曲县| 岳阳市| 秦皇岛市| 河西区| 都江堰市| 桂东县| 锡林浩特市| 达尔| 乳山市| 顺义区| 宁国市| 青铜峡市| 孝昌县| 高雄市| 灌云县| 望谟县| 定西市| 六安市| 安阳县| 灵寿县| 青浦区| 太和县| 肥城市| 镇安县| 南木林县| 新平| 洛扎县| 攀枝花市| 红安县| 六安市| 潜山县| 平和县|