« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
| 公告 |
本博客在此声明所有文章均为转摘,只做资料收集使用。并无其他商业用途。 |
Blog信息 |
blog名称: 日志总数:210 评论数量:205 留言数量:-19 访问次数:920195 建立时间:2007年5月10日 |

| |
[J2SE相关]InvocationHandler 操作例子(切面概念) 文章收藏, 网上资源, 软件技术, 电脑与网络
李小白 发表于 2007/6/6 20:18:19 |
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");}』好了,拷贝上面的自己运行看看就知道了,原来切面就是这么回事。 |
|
|