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; 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.

Comments:

Great work..Thanks a lot

Posted by aasha on October 05, 2012 at 11:55 AM PDT #

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.

Posted by Maneesh on April 11, 2016 at 06:23 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

I share my work experiences as a JVM Sustaining Engineer through this blog

Search

Categories
Archives
« January 2017
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    
       
Today