Call a method before any method invocation of that class in Java -
is there way can have method in class executed every time when method of class invoked.
i'll give brief of scenario here:
class util{ private isconnected(){ if(!xxxapi.connected()) throw new myexception(....) } public createfile(){....} public removefile(){....} }
so, anytime call new util.createfile()
want isconnected() invoked before createfile()
starts. obviously can call isconnected()
everytime in starting of each method, wondering if can have solution.
is there other suggestion/solution such scenario.
you should write invocationhandler
(http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/invocationhandler.html) intercept calls objects, , reflectively (using reflection api) invoke first isconnected()
method followed method call 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 { // isconnectedmethod method isconnectedmethod = util.getclass().getmethod("isconnected"); // invoke method isconnectedmethod.invoke(util); // process result of above call here // invoke method call 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());
Comments
Post a Comment