I want to use
Class.getMethod(String name, Class... parameterTypes)
to find the method I need to invoke with the given parameters, but apparent
The only answer at the moment is to write code to simulate the Java compiler's type promotion rules, an reflectively pick the most appropriate method. Autoboxing and unboxing are just examples of the type promotions the compiler knows about ...
Why don't the Java reflective APIs already do this? I can think of a number of reasons.
Before Java 1.5, the getMethod
class and friends did not understand how to do (for example) promotion of int
to float
. If there wasn't a need pre-1.5, why now?
Adding this kind of stuff will make reflective method calling even slower.
Autoboxing and unboxing can be confusing with non-reflective method invocation. Adding reflection will only add more confusion.
The runtime implementation of the promotion rules will add a class of new runtime error cases that need to be mapped to exceptions and diagnosed by user code. These ones will be particularly tricky. For example, it would have to deal with the reflective equivalent of an ambiguous method call.
The overarching requirement for backwards compatibility means that Sun would have to implement this as new methods. They cannot change the behaviors of the current methods because that would potentially break thousands of customers' existing applications.
There is one final point that relates specifically to the OP's use-case (as described). The OP says that his code does not know whether to expect (for example) a method with an int
or Integer
parameter on the target class. Suppose that the person who wrote the target class provided both overloads ... and the semantics are subtly (or unsubtly) different? No matter what you do, there will be situations where the OP's code picks the overload that the client doesn't expect. Bad.
IMO, it is better for the OP's code to impose some simple API rules that say when it is correct to use primitives versus wrappers.
reflection method look up is not as sophisticated as compiler's. I understand why you need something like that. suppose at runtime you have a method name, and an array of objects as arguments, and you want reflection to give you the exact method based on types of the arguments, but it's more complicated than that. for example:
void f(Integer i){..}
void f(int i){...}
when the argument is type Integer, which one can you choose? An even trickier one:
void f(Integer i, List l){...}
void f(Object o, LinkedList l){...}
compiler has a set of rules to choose the "most specific method" based on static information; if it can't determine it will alert you right away.
you have to simulate the compiler and write an algorithm to find out the "most specific method". (oh, and with consideration of auto-boxing, almost forgot that!)