Question

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
       }
}
Was it helpful?

Solution

I believe you could accomplish that with AspectJ.

OTHER TIPS

The Proxy class only supports proxying interfaces, not classes.

CGLib does have the ability to create proxies from classes and do what you need. The Beans example may provide a good starting point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top