Java - Create an invocation handler?

2.2k views Asked by At

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
       }
}
2

There are 2 answers

1
BillRobertson42 On BEST ANSWER

I believe you could accomplish that with AspectJ.

0
prunge On

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.