I need to call the getName()
method of a Person
class, without knowing the Person
class as compilation time and by using a MethodHandle (instead of normal reflection).
So I'd want this code to work (this code cannot change):
MyGetterAccessor myGA = new MyGetterAccessor(Person.class, "getName", String.class)
assertEquals("Ann", myGA.call(new Person("Ann"));
assertEquals("Beth", myGA.call(new Person("Beth"));
Here's my method handle code, which must not use the word "Person" (this can can change to make this work):
public class MyGetterAccessor {
MethodHandle mh;
public GetterAccessor(Class entityClass, String methodName, Class returnType) {
mh = MethodHandles.lookup().findVirtual(entityClass, methodName, MethodType.methodType(returnType));
}
public Object call(Object entity) {
return mh.invokeExact(entity);
}
}
but this fails with WrongMethodTypeException
. Any suggestion how to fix that?