How to explicitly invoke default method from a dynamic Proxy?

前端 未结 6 835
一向
一向 2020-12-09 15:33

Since Java 8 interfaces could have default methods. I know how to invoke the method explicitly from the implementing method, i.e. (see Explicitly calling a default method i

6条回答
  •  孤城傲影
    2020-12-09 16:08

    If you use a concrete impl class as lookupClass and caller for the invokeSpecial it should correctly invoke the default implementation of the interface (no hack for private access needed):

    Example target = new Example();
    ...
    
    Class targetClass = target.getClass();
    return MethodHandles.lookup()
                        .in(targetClass)
                        .unreflectSpecial(method, targetClass)
                        .bindTo(target)
                        .invokeWithArguments();
    

    This of course only works if you have a reference to a concrete object implementing the interface.

    Edit: this solution will only work if the class in question (Example in the code above), is private accessible from the caller code, e.g. an anonymous inner class.

    The current implementation of the MethodHandles/Lookup class will not allow to call invokeSpecial on any class that is not private accessible from the current caller class. There are various work-arounds available, but all of them require the use of reflection to make constructors/methods accessible, which will probably fail in case a SecurityManager is installed.

提交回复
热议问题