如果您将具体的impl类用作lookupClass和invokeSpecial的调用者,则它应正确调用接口的默认实现(无需黑客进行私有访问):
Example target = new Example();...Class targetClass = target.getClass();return MethodHandles.lookup() .in(targetClass) .unreflectSpecial(method, targetClass) .bindTo(target) .invokeWithArguments();
当然,这仅在您引用实现该接口的具体对象时才有效。
编辑:仅当所涉及的类(上述代码中的示例)可以从调用者代码(例如匿名内部类)进行私有访问时,此解决方案才有效。
MethodHandles /
Lookup类的当前实现不允许在无法从当前调用者类进行私有访问的任何类上调用invokeSpecial。有多种解决方法可用,但是所有这些都需要使用反射来使构造函数/方法可访问,如果安装了SecurityManager,则可能会失败。



