Friday July 25, 2008
How to implement an interface using Reflection
I was trying to use classes and methods of an existing jar using Reflection. And there was an Interface in that jar which I had to implement. Now how to do that with Reflection ??
We can achieve this by using two classes in java.lang.reflect package; Proxy and InvocationHandler.
java.lang.reflect.Proxy class accomplishes implementation of interfaces by dynamically creating a class that implements a set of given interfaces. This dynamic class creation is accomplished with the static getProxyClass and newProxyInstance factory methods. Instance created with newProxyInstance() represents the proxy instance for interface(s) we want to implement.
While creating a Proxy instance, we need to supply it an invocation handler which handles the method calls for this proxy instance. This is accomplished by implementing java.lang.reflect.InvocationHandler. InvocationHandler interface has a method invoke that needs to be implemented A proxy instance forwards method calls to its invocation handler by calling invoke.
Here is the example:
public class ProxyListener implements java.lang.reflect.InvocationHandler {
public ProxyListener() {
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
{
Object result = null;
try {
// Prints the method being invoked
System.out.print("begin method "+ m.getName() + "(");
for(int i=0; iif(i>0) System.out.print(",");
System.out.print(" " +
args[i].toString());
}
System.out.println(" )");
// if the method name equals some method's name then call your method
if (m.getName().equals("someMethod")) {
result = myMethod(args[0]);
}
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("end method " + m.getName());
}
return result;
}
Object myMethod(Object o) {
.........
}
Proxy.newProxyInstance(SomeInterface.getClassLoader(),
Class[]{SomeInterface.class} , new ProxyListener());
And that's about it.
Posted at 11:11AM Jul 25, 2008 by poonam in Sun | Comments[0]