Suppose I have some functional interface like Function and some methods of different classes for which I can take method references, for example:
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;
How I can grab all possible method references converted to instances of Function interface from class A via reflection?
Update:
The question isn't a duplicate of any mentioned in comments so far, but thanks to the both questions mentioned by Holger's in his comment I've managed to do what I've needed:
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;
}
}
}