lhwork 发表于 2006-7-3 11:36:29

 

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

评论
发表评论

您还没有登录,请登录后发表评论

guoyiqi
搜索本博客
最近加入圈子
存档
最新评论
评论排行榜