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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With