假设我有一些函数接口,如 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;
}
}
}