意外的 Class.getMethod 行为 [英] Unexpected Class.getMethod behaviour
问题描述
不久前我有一个类似的问题使用 Class.getMethod 和自动装箱,在您自己的查找算法中实现它是有意义的.但真正让我感到困惑的是以下内容也不起作用:
A while ago I had a similar question when using Class.getMethod and autoboxing, and it made sense to implement this in your own lookup algorithm. But what really confused me a little was that the following is not working either:
public class TestClass
{
public String doSomething(Serializable s)
{
return s.toString();
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException
{
TestClass tc = new TestClass();
Method m = tc.getClass().getMethod("doSomething", String.class);
}
}
String.class 实现了 Serializable 接口,我真的希望它包含在查找方法中.在我自己的查找算法中是否也必须考虑这一点?
String.class implements the Serializable interface and I really expected it to be included in the lookup method. Do I have to consider this in my own lookup algorithms as well?
编辑:我确实阅读了 Javadoc,所以让我强调问题的第二部分:如果是这样,您是否有关于如何快速做到这一点的建议(我已经不得不添加一些自定义匹配和转换算法,但我不希望它变得太慢)?
EDIT: I did read the Javadoc, so let me emphasise the second part of the question: And if so do you have suggestions on how to do that fast (I already had to add some custom matching and converting algorithms and I don't want it to get too slow)?
推荐答案
根据您的编辑,您可以使用 Class#isAssignableFrom()
.这是一个基本的启动示例(将明显的(运行时)异常处理放在一边):
As per your edit, you can make use of Class#isAssignableFrom()
. Here's a basic kickoff example (leaving obvious (runtime) exception handling aside):
package com.stackoverflow.q2169497;
import java.io.Serializable;
import java.lang.reflect.Method;
public class Test {
public String doSomething(Serializable serializable) {
return serializable.toString();
}
public static void main(String[] args) throws Exception {
Test test = new Test();
for (Method method : test.getClass().getMethods()) {
if ("doSomething".equals(method.getName())) {
if (method.getParameterTypes()[0].isAssignableFrom(String.class)) {
System.out.println(method.invoke(test, "foo"));
}
}
}
}
}
这应该将 foo
打印到标准输出.
This should print foo
to stdout.
这篇关于意外的 Class.getMethod 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!