reflection - How do I invoke Java 8 default methods reflectively -


given simple "hello world"ish java 8 interface, how invoke hello() method via reflection?

public interface hello {     default string hello() {         return "hello";     } } 

you use methodhandles that:

import java.lang.invoke.methodhandles; import java.lang.reflect.method; import java.lang.reflect.proxy;  public class reflectivedefaultmethodcallexample {      static interface hello {         default string hello() {             return "hello";         }     }      public static void main(string[] args) throws throwable{          hello target =                 //new hello(){};                 (hello)proxy.newproxyinstance(thread.currentthread().getcontextclassloader(),new class[]{hello.class}, (object proxy, method method, object[] arguments) -> null);         method method = hello.class.getmethod("hello");          object result = methodhandles.lookup()                                      .in(method.getdeclaringclass())                                      .unreflectspecial(method,method.getdeclaringclass())                                      .bindto(target)                                      .invokewitharguments();         system.out.println(result); //hello     } } 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -