Call a method before any method call of this class in Java

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

I will briefly talk about my scenario:

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

So, anytime I call new Util.createFile() , I want this isConnected () to be called before createFile() starts. Obviously, I can call isConnected() every time I run each method, but I was wondering if I could have a different solution.

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

+5
source share
1 answer

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

Example: Util Interface:

 public interface Util { void isConnected(); void createFile(); void removeFile(); } 

Use call 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()); 
+9
source

All Articles