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");
}
InvocationHandler 操作例子
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
python协程(asyncio)实现爬虫例子
使用python协程实现异步爬取网站。
python 协程 爬虫 -
Redis基础操作
redis知识梳理
redis Redis -
Java代理:Proxy InvocationHandler
public interface IHelloWorld { void sayHello(); } public class&n
Java Proxy 代理 InvocationHandler -
数据操作例子
'----------------------------------'一個打開數據庫並返回一個DataTable'-------------------------
sql html ide taro microsoft