How to create a proxy for an interface without creating a class that implements it?
I have a specific example: I have an interface, Contact, and you need to create a proxy object that acts like a Contact. This proxy object will be used to run some TestNG tests.
I tried using the JDK approach, but could only find examples that needed the actual implementation of this interface.
I also found that jasssist can help me with this problem and tried to implement a simple example that seems to work until I get an Out of Memory error. Here is a snippet of what I'm 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) {
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 createMock () method parameter will be an interface.
thank