1

I have an interface with default methods only.

interface Some {
    default void doSome() {
    }
}

And I'm creating some sort of proxy instance from it.

(Some) getProxy(new Class<?>[]{Some.class}, new Some() {});

Now I want some utility method of doing it for any interface.

Is there any nice way to do that?

<T> T static proxy(final Class<T> clazz) {
    // @@? How can I do `new T(){}` from the class?
}
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • Seems like an unusual approach to solve _something_, could you provide information about why you try to achieve this? – Glains Mar 09 '20 at 10:36
  • what's the point of the proxy when you already get an instance of the interface with `new Some() {}`? – Clashsoft Mar 09 '20 at 10:40

1 Answers1

1

It is possible to call a default interface method from a dynamic proxy (java.lang.reflect.Proxy) using java.lang.invoke.MethodHandles.

public interface Some {

  default void doSome() {
    System.out.println("something...");
  }

  @SuppressWarnings("unchecked")
  static <T> T getProxy(Class<T> clazz) {
    return (T) Proxy.newProxyInstance(
        clazz.getClassLoader(),
        new Class[]{clazz},
        (proxy, method, args) -> MethodHandles.lookup()
            .in(clazz)
            .unreflectSpecial(method, clazz)
            .bindTo(proxy)
            .invokeWithArguments());
  }

  public static void main(String[] args) {
    Some some = getProxy(Some.class);
    some.doSome();
  }
}

The main method prints:

something...
Eugene Khyst
  • 9,236
  • 7
  • 38
  • 65