Java getMethod with subclass parameter
Posted
by
SelectricSimian
on Stack Overflow
See other posts from Stack Overflow
or by SelectricSimian
Published on 2013-11-10T03:49:22Z
Indexed on
2013/11/10
3:53 UTC
Read the original article
Hit count: 113
I'm writing a library that uses reflection to find and call methods dynamically. Given just an object, a method name, and a parameter list, I need to call the given method as though the method call were explicitly written in the code.
I've been using the following approach, which works in most cases:
static void callMethod(Object receiver, String methodName, Object[] params) {
Class<?>[] paramTypes = new Class<?>[params.length];
for (int i = 0; i < param.length; i++) {
paramTypes[i] = params[i].getClass();
}
receiver.getClass().getMethod(methodName, paramTypes).invoke(receiver, params);
}
However, when one of the parameters is a subclass of one of the supported types for the method, the reflection API throws a NoSuchMethodException
. For example, if the receiver's class has testMethod(Foo)
defined, the following fails:
receiver.getClass().getMethod("testMethod", FooSubclass.class).invoke(receiver, new FooSubclass());
even though this works:
receiver.testMethod(new FooSubclass());
How do I resolve this? If the method call is hard-coded there's no issue - the compiler just uses the overloading algorithm to pick the best applicable method to use. It doesn't work with reflection, though, which is what I need.
Thanks in advance!
© Stack Overflow or respective owner