7

Is there a way that I can have a method in a class executed every time when any method of that class is invoked.

I'll give a brief of my scenario here:

Class Util{

   private isConnected(){
      if(!xxxapi.connected())
            throw new MyException(....)
}
   public createFile(){....}
   public removeFile(){....}
}

So, anytime I call new Util.createFile() I want that isConnected() is invoked before createFile() actually starts. Obviously I can call isConnected() everytime in the starting of each method, but I was wondering if I can have another solution.

Is there any other suggestion/solution for such a scenario.

Dushyant Gupta
  • 507
  • 1
  • 5
  • 24
  • You should probably explore reflection apis. Using reflection you can achieve this. If you are ok to use framework, probably you can look into Spring AOP which is there for your use case. – sakura Sep 07 '16 at 12:19
  • You could use AOP but unless you want to call that method at the start _every_ method you're probably not getting much out of that (in terms of developer performance). – Thomas Sep 07 '16 at 12:20
  • I think you should look into annotations for a more elegant solution – BigMike Sep 07 '16 at 12:20
  • You can check AspectJ – Rahul Tripathi Sep 07 '16 at 12:23
  • you can use cglib and spring : [refer](http://stackoverflow.com/questions/576918/how-do-i-intercept-a-method-invocation-with-standard-java-features-no-aspectj-e) – Shatayu Darbhe Sep 07 '16 at 12:37

1 Answers1

10

You should write a InvocationHandler (http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/InvocationHandler.html) that would intercept calls to your objects, and then reflectively (using reflection API) invoke first the isConnected() method followed by the method to which the call was made.

Sample: Util Interface:

public interface Util {

    void isConnected();

    void createFile();

    void removeFile();

}

Util invocation handler:

public class UtilInvocationHandler implements InvocationHandler {

    private Util util = new UtilImpl();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        // look up isConnectedMethod
        Method isConnectedMethod = util.getClass().getMethod("isConnected");

        // invoke the method
        isConnectedMethod.invoke(util);

        // process result of the above call here

        // invoke the method to which the call was made
        Object returnObj = method.invoke(util, args);

        return returnObj;
    }

    private static class UtilImpl implements Util {
        public void isConnected(){
            System.out.println("isConnected()");
        }

        public void createFile(){
            System.out.println("createFile()");
        }

        public void removeFile(){
            System.out.println("removeFile()");
        }
    }
}

Object initialization:

    Util util = (Util) Proxy.newProxyInstance(
                                   Util.class.getClassLoader(), 
                                   new Class[] {Util.class}, 
                                   new UtilInvocationHandler());
Stugal
  • 850
  • 1
  • 8
  • 24