Get MethodHandle from lambda object

2019-05-31 03:53发布

问题:

From java.lang.invoke.LambdaMetafactory:

The recommended mechanism for evaluating lambda expressions is to desugar the lambda body to a method, invoke an invokedynamic call site whose static argument list describes the sole method of the functional interface and the desugared implementation method, and returns an object (the lambda object) that implements the target type.

And from inspection this is at least what Oracle JDK does.

My question: given a lambda object is there a way to find the name (or a handle to) the implementation method? Alternately, given a list of implementation methods, is there a way to tell which one corresponds to a given lambda object?

回答1:

You could access the ConstantPool of the lambda class (i.e. by using sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(class)) and then search for the method reference. You have to ignore the object constructor as well as autoboxing/unboxing method references, the remaining method reference is the implementing method.