1

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
       }
}
aryaxt
  • 76,198
  • 92
  • 293
  • 442

2 Answers2

3

I believe you could accomplish that with AspectJ.

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57
  • +1. To be more specific, it doesn't make much sense to have `Loggable` as a base class. What if you had some other composable behavior you also wanted to include? AOP seems like a better approach. – Dan Dec 05 '11 at 14:01
2

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.

prunge
  • 22,460
  • 3
  • 73
  • 80