Hello,
How can one create a proxy for an interface without creating a class that implements it?
I have a concrete example: I have an interface, Contact, and need to create a proxy object that acts as a Contact. This proxy object will be used for running some TestNG tests.
I have tried using the JDK approach but could find only examples that needed an actual implementation of that interface.
I also found that jasssist may help me in this problem and tried implementing a simple example that seems to be working until I get an Out of Memory error. Here is a snippet of what I am doing:
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory
protected final T createMock(final Class<T> clazz) {
final ProxyFactory factory = new ProxyFactory();
factory.setInterfaces(new Class[] { clazz });
factory.setFilter(new MethodFilter() {
public final boolean isHandled(final Method m) {
// ignore finalize()
return !m.getName().equals("finalize");
}
});
final MethodHandler handler = createDefaultMethodHandler();
try {
return (T) factory.create(new Class<?>[0], new Object[0], handler);
} catch (final Exception e) {
e.printStackTrace();
}
return null;
}
private MethodHandler createDefaultMethodHandler() {
return new MethodHandler() {
public final Object invoke(final Object self,
final Method thisMethod, final Method proceed,
final Object[] args) throws Throwable {
System.out.println("Handling " + thisMethod
+ " via the method handler");
return thisMethod.invoke(self, args);
}
};
}
Remember that the parameter of the createMock() method will be an interface.
Thanks