title: How to create a proxy of an interface in Java?
body: <p>How can one create a proxy for an interface without creating a class that implements it?</p>
  
  <p>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.</p>
  
  <p>I have tried using the JDK approach but could find only examples that needed an actual implementation of that interface.</p>
  
  <p>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:</p>
  
  <pre><code>import javassist.util.proxy.MethodFilter;
  import javassist.util.proxy.MethodHandler;
  import javassist.util.proxy.ProxyFactory
  
  protected final T createMock(final Class&lt;T&gt; 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&lt;?&gt;[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);
          }
      };
  }
  </code></pre>
  
  <p>Remember that the parameter of the createMock() method will be an interface.</p>
  
  <p>Thanks</p>