java - Java8 dynamic proxy and default methods -
having dynamic proxy interface default methods, how invoke default method? using defaultmethod.invoke(this, ...)
proxy invocation handler called (which somehow correct, cause have no implementing class interface).
i have workaround using asm create class implementing interface , delegating such calls instance of class. not solution, if default method calls other interface methods (you delegator ping-pong). jls surprisingly silent question...
here little code example:
class="lang-java prettyprint-override">public class java8proxy implements invocationhandler { public interface withdefaultmethod { void somemethod(); default void somedefaultmethod() { system.out.println("default method invoked!"); } } @test public void invoketest() { withdefaultmethod proxy = (withdefaultmethod) proxy.newproxyinstance( withdefaultmethod.class.getclassloader(), new class<?>[] { withdefaultmethod.class }, this); proxy.somedefaultmethod(); } @override public object invoke(object proxy, method method, object[] args) throws throwable { // assuming not knowing interface before runtime (i wouldn't utilize // proxy, i?) // here line printed out? // loop // method.invoke(this, args); homecoming null; } }
you can utilize methodhandles type in invocationhandler.
if (method.isdefault()) { homecoming methodhandles.lookup() .in(method.getdeclaringclass()) .unreflectspecial(method, method.getdeclaringclass()) .bindto(proxy) .invokewitharguments(args); }
java java-8
No comments:
Post a Comment