【发布时间】:2011-12-05 02:51:35
【问题描述】:
我正在尝试实现一个生成对象并拦截所有公共方法的工厂类。
我在这里尝试调用 2 个方法。 1:已经调用的方法 2:我的基础中的一个方法。 知道如何实现这一目标吗?
public class LoggerFactory {
public LoggerFactory() {
}
// Clazz is always a class inheriting from Loggable
public Object newInstance(Class clazz) {
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, handler);
}
private InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Call logStartingTime on object
// Call invoked method on object
// Call logEndingTime on object
return null;
}
};
}
我的抽象类:
public abstract class Loggable {
void logStartingTime() {
log.info(“start time = ” + new Date());
// also log some info about the state of the object
}
void logEndingTime() {
log.info(“ending time = ” + new Date());
// also log some info about the state of the object
}
}
【问题讨论】:
标签: java method-invocation invocationhandler