Raidmaster
Raidmaster

Reputation: 613

Java Reflection, getting parameter types

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

Answers (1)

Jon Skeet
Jon Skeet

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:

  • Find all methods with the right name and the right number of parameters.
  • Check each method to see whether all the argument values are assignable to the corresponding parameter types (see Class.isAssignableFrom - you may need to handle primitives separately).
  • If there are multiple matching methods, apply some rules to determine which to call. Those rules don't have to be the same as Java, but you need to make sure they're clear.

Upvotes: 3

Related Questions