If I run the following program:
class Runit{
public static void main(String[] argsWut) throws Exception {
String arg = "what?";
Class[] parameters = { new Object().getClass() };
Object[] args = { arg };
System.out.println("".getClass().getMethod("equals",parameters).invoke("what?",args));
}
};
I get the following on the command line:
true
On the other hand, if I modify the parameters line a little:
class Runit{
public static void main(String[] argsWut) throws Exception {
String arg = "what?";
Class[] parameters = { arg.getClass() }; // changed a little here so it's a bit more dynamic --
Object[] args = { arg };
System.out.println("".getClass().getMethod("equals",parameters).invoke("what?",args));
}
};
I get:
Exception in thread "main" java.lang.NoSuchMethodException: java.lang.String.equals(java.lang.String)
at java.lang.Class.getMethod(Class.java:1605)
at test.Runit.main(Runit.java:7)
From this one example it looks to me as though the getMethod method only works with exact parameters. Is there a way to get some form of a “best fit” method? e.g. If an exact match exists, it would return that method, but if no exact match exists, it can return any method that could accept my given arguments.
From the documentation for
getMethod():(Emphasis mine.)
What you are asking for is to have reflection perform overload resolution for you. And apparently it won’t. If you really need this functionality, you can either 1) give up on using reflection and invoke the method directly, or 2) if that’s not possible, look up the rules for overload resolution in Java (you could start here), use
getMethods()to determine the available methods, and then perform overload resolution manually. Fun times, I know.Edit: As other answerers have pointed out, someone has already taken the time to do that for you. Cool!