以下是几个简单的类:
[code="java"]
//接口
public interface ItemMgr {
void add();
}
//实现
public class ItemMgrImpl implements ItemMgr {
public void add() {
System.out.println("Add an Item");
}
}
//处理日志
public class LogHandler implements InvocationHandler {
private Object target;
public LogHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("Log Start Write...");
Object res = method.invoke(target, args);
System.out.println("Log End Write...");
return res;
}
}
//计算方法运行时间
public class TimeHandler implements InvocationHandler {
private Object target;
public TimeHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long start = System.currentTimeMillis();
System.out.println("starttime : " + start);
Object res = method.invoke(target, args);
long end = System.currentTimeMillis();
System.out.println("time : " + (end-start));
return res;
}
}
//测试方法
public class TestProxy {
public static void main(String[] args) throws Exception {
ItemMgr mgr = new ItemMgrImpl();
TimeHandler th = new TimeHandler(mgr);
LogHandler lh = new LogHandler(th);
ItemMgr m = (ItemMgr)Proxy.newProxyInstance(mgr.getClass().getClassLoader(),
mgr.getClass().getInterfaces(),
th);
m.add();
}
}
[/code]
[size=small]运行测试方法会抛出java.lang.IllegalArgumentException: object is not an instance of declaring class异常
我只是在计算时间外面套了一层处理日志,望指教。[/size]