从 lambda 对象获取 MethodHandle

Get MethodHandle from lambda object

来自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.

从检查来看,这至少是 Oracle JDK 所做的。

我的问题:给定一个 lambda 对象,有没有办法找到实现方法的名称(或句柄)?或者,给定一个实现方法列表,有没有办法判断哪个对应于给定的 lambda 对象?

您可以访问 lambda class 的 ConstantPool(即通过使用 sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(class)),然后搜索方法参考。您必须忽略对象构造函数以及 autoboxing/unboxing 方法引用,剩余的方法引用是实现方法。