Gili
Gili

Reputation: 90023

How to compare MethodHandle instances?

How do I compare two MethodHandle instances? I am expecting the function to return true if the handles point to the same method. It doesn't look like the class overrides equals() or hashcode(). Is it safe to use the equality operator (==)?

Upvotes: 1

Views: 209

Answers (1)

Holger
Holger

Reputation: 298153

First of all, MethodHandles may not only encapsulate a target method but also a behavior. E.g. you may have two method handles pointing to the same method but one encapsulating a non-virtual (super. …) call and one representing an ordinary virtual invocation. These handles can’t be equal.

Besides that, there is no defined equality for MethodHandles anyway. They are there to allow invocation but not introspection:

JVMSpec §5.4.3.5. Method Type and Method Handle Resolution:

An implementation of the Java Virtual Machine is not required to intern method types or method handles. That is, two distinct symbolic references to method types or method handles which are structurally identical might not resolve to the same instance of java.lang.invoke.MethodType or java.lang.invoke.MethodHandle respectively.


However, starting with Java 8 there is a feature that allows to introspect a direct MethodHandle, Lookup.revealDirect. For handles for which this operation succeeds, you can use the information in the returned MethodHandleInfo to find out whether two handles point to the same method.

Upvotes: 5

Related Questions