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 阅读(205) 评论(0)  编辑  收藏 所属分类: j2se


只有注册用户登录后才能发表评论。


网站导航: