3

下面是代码片段,我正在尝试usingClass使用 REFLECTION 调用该方法。当我传递 Child 类型的对象时,直接调用该usingClass()方法(无反射)有效,但当我尝试使用 Reflection 实现相同的事情时,它会抛出NoSuchMethodFoundException. 想了解我是否遗漏了什么或者这背后是否有任何逻辑?请帮忙

package Reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class TestMethodInvocation {

    /**
     * @param args
     */
    public static void main(String[] args) {
        TestMethodInvocation test = new TestMethodInvocation();
        Child child = new Child();
        Parent parent = (Parent)child;
        Class<? extends Parent> argClassType = parent.getClass();
        Class<? extends TestMethodInvocation>  thisClassType = test.getClass();

        test.usingClass(child);

        Method methodToCall;
        try {
            methodToCall = thisClassType.getDeclaredMethod("usingClass", argClassType);
            methodToCall.invoke(test, parent);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void usingClass(Parent p){
        System.out.println("UsingClass: " + p.getClass());
    }


}

输出如下。

UsingClass: class Reflection.Child
java.lang.NoSuchMethodException: Reflection.TestMethodInvocation.usingClass(Reflection.Child)
    at java.lang.Class.getDeclaredMethod(Unknown Source)
    at Reflection.TestMethodInvocation.main(TestMethodInvocation.java:20)
4

2 回答 2

4

您的代码不起作用的原因getClass()是动态绑定的。转换为 Parent 不会影响对象的运行时类型,因此变量childparent包含相同的类对象。除非您通过或类似的方式显式查询您的实例的父类,getGenericSuperclass()否则您将不得不使用dystroy 提到的静态方式。

于 2012-06-11T06:52:32.910 回答
1

You should use

methodToCall = thisClassType.getDeclaredMethod("usingClass", Parent.class);

because the precise exact class of parent (which is Child), is used at runtime and the type of the variable holding it changes nothing.

Another (too heavy) way to solve it would be :

Class<? extends Parent> argClassType2 = (new Parent()).getClass();
...
    methodToCall = thisClassType.getDeclaredMethod("usingClass", argClassType2);
于 2012-06-11T06:49:45.583 回答