前一段时间我在使用Class.getMethod和autoboxing时遇到了类似的问题,在你自己的查找算法中实现它是有意义的.但真正让我感到困惑的是,以下内容无效:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
String.class实现了Serializable接口,我真的希望它包含在查找方法中.我是否也必须在自己的查找算法中考虑这一点?
编辑:我确实读过Javadoc,所以让我强调问题的第二部分:如果是这样,你有关于如何快速做到这一点的建议(我已经不得不添加一些自定义匹配和转换算法,我不想要它太慢了?)
根据您的编辑,您可以使用Class#isAssignableFrom()
.这是一个基本的启动示例(抛开明显的(运行时)异常处理):
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"));
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这应该打印foo
到stdout.