I am trying to implement a factory class that generates objects and intercept all public methods.
I am trying to invoke 2 methods here. 1:the already invoked method 2: a method in my base. Any idea how I can achieve this?
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;
}
};
}
My Abstract class:
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
}
}
I believe you could accomplish that with AspectJ.