Matching Class arrays
I'm writing a routine to invoke methods, 开发者_JAVA百科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.
if (Arrays.equals(methodParams, searchParams)) {
// ...
}
Your first method is not actually comparing the array elements, it's comparing the array references, which won't be the same. If you think the second piece of code is ugly, you might want to look at Arrays.equals(Object[] a, Object[] a2), which will actually compare two arrays in a pairwise fashion (exactly what you're doing in the second case).
精彩评论