使用java.lang.reflect.getMethod和多态方法 [英] Using java.lang.reflect.getMethod with polymorphic methods
问题描述
请考虑以下代码段:
public class ReflectionTest {
public static void main(String[] args) {
ReflectionTest test = new ReflectionTest();
String object = new String("Hello!");
// 1. String is accepted as an Object
test.print(object);
// 2. The appropriate method is not found with String.class
try {
java.lang.reflect.Method print
= test.getClass().getMethod("print", object.getClass());
print.invoke(test, object);
} catch (Exception ex) {
ex.printStackTrace(); // NoSuchMethodException!
}
}
public void print(Object object) {
System.out.println(object.toString());
}
}
getMethod ()
显然不知道 String
可以被提供给期望 Object
(事实上,它的文档说它查找具有指定名称的方法和完全相同的形式参数类型)。
getMethod()
is obviously unaware that a String
could be fed to a method that expects an Object
(indeed, it's documentation says that it looks for method with the specified name and exactly the same formal parameter types).
是否有反复查找方法的简单方法,如 getMethod()
,但考虑到多态性,以便上面的反射示例可以找到 print(Object )
用查询的方法(print,String.class)
参数?
Is there a straightforward way to find methods reflectively, like getMethod()
does, but taking polymorphism into account, so that the above reflection example could find the print(Object)
method when queried with ("print", String.class)
parameters?
推荐答案
建议使用 Class.isAssignableFrom()
样本来查找打印(String)
Method[] allMethods = c.getDeclaredMethods();
for (Method m : allMethods) {
String mname = m.getName();
if (!mname.startsWith("print") {
continue;
}
Type[] pType = m.getGenericParameterTypes();
if ((pType.length != 1)
|| !String.class.isAssignableFrom(pType[0].getClass())) {
continue;
}
}
这篇关于使用java.lang.reflect.getMethod和多态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!