Proposal: java.lang.reflect.Proxy and default methods
Jake Wharton
jakewharton at gmail.com
Sun Jun 5 06:28:27 UTC 2016
On Fri, Jun 3, 2016 at 10:58 AM Peter Levart <peter.levart at gmail.com> wrote:
> InvocationHandler gets invoked for default methods, but it
> has not provision to forward such calls to the default implementations
> in the interfaces.
>
This isn't quite true. You can use MethodHandles to invoke the default
method if the interface is public:
Object returnValue = MethodHandles.lookup()
.in(declaringClass)
.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
If the interface is not public, things get a bit more tricky since you need
an instance which ignores the visibility. The only way to get at this is
through creating your own trusted instance for the interface type:
Constructor<Lookup> constructor =
Lookup.class.getDeclaredConstructor(Class.class, int.class);
constructor.setAccessible(true);
Object returnValue = constructor.newInstance(declaringClass, -1 /*
trusted */)
.unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
That said, I'm all for an API that makes this easier! Please make sure it
handles non-public interface types as well.
More information about the core-libs-dev
mailing list