X

Poonam Bajaj's Blog

How to implement an interface using Reflection

Poonam Parhar
Consulting Member of Technical Staff
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; i if(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) {

.........
}

Now we use newProxyInstance to create an instance of, say interface SomeInterface, passing it the invocation handler.
Proxy.newProxyInstance(SomeInterface.getClassLoader(),
Class[]{SomeInterface.class} , new ProxyListener());

and you get the proxy instance for SomeInterface. Use it wherever you need an object of SomeInterface.
And that's about it.

Join the discussion

Comments ( 2 )
  • aasha Friday, October 5, 2012

    Great work..Thanks a lot


  • Maneesh Monday, April 11, 2016

    Thanks , it was quite useful. I needed to implement some interfaces provided by Apple for running java application on Mac OSX, in a way that the code does not explicitly import apple specific APIs. Used this method to create a proxy to handle the OSX specific events.


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.