Reputation: 613
I have a method callMethod that takes arguments: methodName (String) and parameters(Object[]). Now, everything seemed fine for me at the beginning, but I've stumbled upon a problem. You have to know the type of the Object to use reflection. So far I was determining it in such way:
Class[] getParameterTypes(Object[] parameters) {
Class[] parameterTypes = new Class[parameters.length];
for (int i = 0; i < parameters.length; i++) {
parameterTypes[i] = parameters[i].getClass();
}
return parameterTypes;
}
The callMethod is used to invoke method from external source. And it seems to fail when those methods have primitive parameters as types, or interfaces (List etc.) and I know why.
My question is: Is there any way around this to keep it that/similar way, or the only solution is to pass the type information (f.e Integer.TYPE for primitives etc.) to the method mentioned above:
callMethod(String methodName, Object[] parameters, Class[] parameterTypes);
Thanks for any help.
Upvotes: 2
Views: 723
Reputation: 1499770
Your code would also fail if the caller expected overload resolution based on their variable types. For example:
void foo(String x) {}
void foo(Object x) {}
Object x = "text";
foo(x);
... will call foo(Object)
rather than foo(String)
, but your reflection code will call foo(String)
.
Now, we don't really know enough about your use case to say whether that's a problem. If the caller does know exactly which method they want to call, with which parameter types, then it's best if they pass them.
If the above situation just wouldn't occur within your context, you may well want to perform some sort of rudimentary overload resolution within your reflection code:
Class.isAssignableFrom
- you may need to handle primitives separately).Upvotes: 3