About commons-invoke

1. The invocation framework

2. Usage

The invocation framework

The invocation framework defines the Invocable interface which represent an object that has InvocableFunctions that can be invoked. There are a few uses for the framework:

  1. As a wrapper framework for reflection for optimizing method invocation. For example, the AbstractInvocable uses the reflection for method invocation by default, but can optionally take implemented InvocableFunction for doing the compiled method invocation
  2. As a wrapper framework for reflection for proxying method invocation. For example, the AbstractInvocable uses the reflection for method invocation but optionally take implemented InvocableFunction to proxy the reflection call
  3. As arbitrary invocation framework for application independant of reflection (e.g. defines a set of functions on an object independant of what java methods the object really provides)

Example

Using common-invoke as reflection wrapper

Let supposed that you have a method callMeALot in an class MyObject that is called frequently in your application, but as the requirement of the design you are allowed to call it using java reflection api

MyObject obj = new MyObject();

//...later somewhere in your application...
Method m = obj.getMethod("callMeALot", argTypes);
m.invoke(args);
                
Supposed that method callMeALot is called a lot (10000 per seconds) and the reflection call the slowing down the application. The following code shows how to replace the java reflection api with the common-invoke
MyObject obj = new MyObject();
Invocable inv = new ReflectionWrapperInvocable(obj);

//...later somewhere in your application
inv.invoke("callMeALot", args); //notice this is simpler than reflection api
                
The last line in the source above still uses the java reflection api to make the action method call the callMeALot. But now, the method can be optimize by doing the following
MyObject obj = new MyObject();
Invocable inv = new ReflectionWrapperInvocable(obj);
inv.addFunction(new AbstractInvocableFunction("callMeALot", new Class[] {}){
    public Object invoke(Object obj, Object[] args){
        return ((MyObject)obj).callMeALot();
    }
}

//...later somewhere in your application
inv.invoke("callMeALot", args); //this time, it will do the direct call
                
While the java reflection api is in general fast, the benchmark shows that the optimization uses half the time required by the java reflection api.