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;
}
}
}