将 java.lang.reflect.getMethod 与多态方法一起使用

2022-01-24 00:00:00 polymorphism reflection java

考虑以下代码段:

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) 参数查询时的 code> 方法?

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() 示例来查找 print(String)

suggest the use of Class.isAssignableFrom() sample for finding print(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;
        }
     }

相关文章