我正在尝试实现一个生成对象并拦截所有公共方法的工厂类。
我试图在这里调用 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
}
}