How can I instantiate an interface at runtime?

Jin Kwon :

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?
}
Evgeniy Khyst :

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...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195416&siteId=1