Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a proxy of an interface in Java?

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

like image 281
virgium03 Avatar asked Dec 22 '22 22:12

virgium03


1 Answers

You can use the method newProxyInstance of java.lang.reflect.Proxy. Ex:

    Proxy.newProxyInstance(iClazz.getClassLoader(),
        new Class[]{iClazz},
        new YourInvocationHandler())

iClazz is the class of your interface and YourInvocationHandler is an instance of java.lang.reflect.InvocationHandler

like image 142
Bateramos Avatar answered Dec 28 '22 08:12

Bateramos