0

好的,我确实了解 Java 反射是如何工作的。但是我所做的与反射教程中显示的有点不同。现在我想在下面调用一个方法,该方法通过使用反射调用方法返回。

   class Foo{
          private String str = "";

          public Foo(String str){
              str = this.str;
          }

          public void goo(){
            System.out.println(this.str);
          }
    }

    class Bar{
         public Foo met(String str){
              return new Foo(str); 
         }
    }

    class Hee{
         public static void main(String [] args) throws Exception{
                Class cls = Class.forName("Bar");
                Object obj = cls.newInstance();

                Class [] types = {String.class};
                String [] arr = {"hello"};
                Method method = cls.getMethod("met",types);

        Object target = method.invoke(obj, arr);

                target.goo(); //here where the error occurs
                // 123456
        }
    }

现在,我很大程度上依赖于我的经验,即我method.invoke()将返回由反映的方法返回的方法返回的对象。但似乎它不起作用..我调试了我的代码,似乎它没有返回任何东西。我做错了什么?如果我做错了什么请告诉我

4

3 回答 3

5

可能需要将target对象转换为foo type.

((foo)target).goo();
于 2012-11-05T07:25:35.953 回答
1

为了在一个变量中调用一个类的方法,你应该声明那个类的变量:

Foo target = (Foo) method.invoke(obj, arr); // And do some casting.
target.goo();
于 2012-11-05T07:31:47.603 回答
0

好吧,除了反射(Test 类)中缺少演员表之外,您的 Foo 类还有一个错误。您的代码应该看起来像这样。

class Foo {
    private String str = ""; 

    public Foo(String str) {
        this.str = str; //You had str=this.str;
    }

    public void goo() {
        System.out.println(this.str);
    }
}

class Bar {
    public Foo met(String str) {
        return new Foo(str);
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        Class cls = Class.forName("Bar");
        Bar obj = (Bar) cls.newInstance();
        Class[] types = { String.class };
        String[] arr = { "hello" };
        Method method = cls.getMethod("met", types);
        Foo target = (Foo) method.invoke(obj, arr);
        target.goo(); 
   }
}
于 2012-11-05T07:41:55.363 回答