假设我有一些像Function这样的函数接口和一些不同类的方法,我可以为它们提取方法参考,例如:
class A {
public int getPrimitive() { return 0; }
public Integer getBoxed() { return 0; }
public static int getStaticPrimitive(A a) { return 1; }
}
Function<A, Integer> primitive = A::getPrimitive;
Function<A, Integer> boxed = A::getBoxed;
Function<A, Integer> staticPrimitive = A::getStaticPrimitive;
如何通过反射获取从A类转换为Function接口实例的所有可能的方法引用?
到目前为止,问题与评论中提到的任何问题都不重复,但多亏了Holger在评论中提到的两个问题,我已经设法做了我需要的事情:
class Test {
public static void main(String[] args) throws Throwable {
HashMap<String, Function<A, Integer>> map = new HashMap<>();
Collection<MethodType> supportedTypes = Arrays.asList(
MethodType.methodType(int.class, A.class),
MethodType.methodType(Integer.class, A.class)
);
MethodType inT = MethodType.methodType(Function.class);
MethodHandles.Lookup l = MethodHandles.lookup();
for (Method m : A.class.getDeclaredMethods()) {
MethodHandle mh = l.unreflect(m);
if (!supportedTypes.contains(mh.type())) {
continue;
}
map.put(m.getName(), (Function<A, Integer>) LambdaMetafactory.metafactory(
l, "apply", inT, mh.type().generic(), mh, mh.type()).getTarget().invoke());
}
A a = new A();
map.forEach((name, op) -> System.out.println(name + "(a) => " + op.apply(a)));
}
static class A {
public int getPrimitive() {
return 0;
}
public Integer getBoxed() {
return 1;
}
public static Integer getStaticBoxed(A a) {
return 2;
}
public static int getStaticPrimitive(A a) {
return 3;
}
}
}