I’m writing a routine to invoke methods, found by a name and an array of parameter Class values
Matching the Method by getName works, but when trying to match the given Class[] for parameters, and Method.getParameterTypes(), I’m having trouble.
I assumed that this would work:
Class[] searchParams = new Class[] { float.class, String.class };
Class[] methodParams = m.getParameterTypes();
if(methodParams == searchParams) {
m.invoke(this, paramValues);
}
But apparantly not - m.invoke is never reached. I've checked, and methodParams gives the same classes as searchParams.
The code below works, and picks the right method, but it seems like a very dirty way of doing things, I'm sure I'm missing something obvious.
Class[] searchParams = new Class[] { float.class, String.class };
Class[] methodParams = m.getParameterTypes();
boolean isMatch = true;
for(int i = 0; i < searchParams.length; i++) {
if(!searchParams.getClass().equals(methodParams.getClass())) {
isMatch = false;
}
}
if(isMatch) {
m.invoke(this, paramValues);
}
Arrays are objects, not primitives. Using
==on objects only compares if they both points to the same reference, while you actually want to compare every individual array item separately.You want to use
Arrays#equals()for this.