是否可以使用MethodHandle检索正在引用的成员?
MethodHandle mh = MethodHandles.lookup().findStatic(..., ..., ...);
java.lang.reflect.Method method = convertToReflection(mn); //???
正确的术语是“直接方法句柄”,以强调与类成员的直接连接这一事实。或者正如the documentation所说:
直接方法句柄表示方法,构造函数或字段,没有任何插入参数绑定或其他转换。
术语“绑定”宁愿建议存在预绑定参数值或绑定接收器,它们不再与普通的Reflection对象匹配。
Java 8允许通过MethodHandle
从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);
}
}
它受限于Reflection对象与您提供的Lookup
对象描述的上下文兼容,即当尝试通过名称和类型查找同一成员时,它将在该查找对象中成功。