Search code examples
javareflectionbytecode

Convert BoundMethodHandle to reflection


Is it possible to retrieve the member that is being referenced to with a MethodHandle?

MethodHandle mh = MethodHandles.lookup().findStatic(..., ..., ...);
java.lang.reflect.Method method = convertToReflection(mn); //???

Solution

  • The correct term is “direct method handle”, to emphasize the fact that there is a direct connection to a member of a class. Or as the documentation puts it:

    A direct method handle represents a method, constructor, or field without any intervening argument bindings or other transformations.

    The term “bound” would rather suggest that there are pre-bound parameter values or a bound receiver, which would not match a plain Reflection object anymore.

    Java 8 allows to get the member from a MethodHandle via MethodHandles.Lookup.revealDirect(…):

    public class Tmp {
        public static void main(String[] args) throws ReflectiveOperationException {
            MethodHandles.Lookup lookup = MethodHandles.lookup();
            MethodHandle mh = lookup
              .findStatic(Tmp.class, "main", MethodType.methodType(void.class, String[].class));
            Method method = lookup.revealDirect(mh).reflectAs(Method.class, lookup);
            System.out.println(method);
        }
    }
    

    It’s constrained to Reflection objects compatible with the context described by the Lookup object you provide, i.e. it will work when trying to lookup the same member via name & type would succeed with that lookup object.