匹配类数组
我正在编写一个例程来调用方法,通过名称和参数类值数组找到
通过 getName 匹配方法的方法,但是当尝试匹配参数的给定 Class[] 和 Method.getParameterTypes() 时,我'我遇到麻烦了。
我认为这会起作用:
Class[] searchParams = new Class[] { float.class, String.class };
Class[] methodParams = m.getParameterTypes();
if(methodParams == searchParams) {
m.invoke(this, paramValues);
}
但显然不是 - m.invoke 从未达到。我检查过,methodParams 提供与 searchParams 相同的类。
下面的代码有效,并选择了正确的方法,但这似乎是一种非常肮脏的做事方式,我确信我错过了一些明显的东西。
Class[] searchParams = new Class[] { float.class, String.class };
Class[] methodParams = m.getParameterTypes();
布尔值 isMatch = true;
for(int i = 0; i < searchParams.length; i++) {
if(!searchParams.getClass().equals(methodParams.getClass())) {
匹配=假;
}
}
if(isMatch) {
m.invoke(this, paramValues);
}
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); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
数组是对象,而不是基元。在对象上使用
==
仅在它们都指向相同引用时进行比较,而您实际上希望分别比较每个单独的数组项。您想要使用
Arrays#equals()
为此。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.您的第一个方法实际上并不是比较数组元素,而是比较数组引用,这不会相同。如果您认为第二段代码很难看,您可能需要查看 Arrays.equals(Object[] a, Object[] a2),实际上会比较两个数组以成对的方式(正是你在第二种情况下所做的)。
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).