通过Java中的反射从调用的方法调用返回方法

Mp *_*ega 0 java reflection

好的,我确实理解Java Reflection的工作原理.但我正在做的事情与反思教程中显示的有点不同.现在我想要的是调用一个方法,该方法通过使用反射调用方法返回.

   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
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Sub*_*der 5

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

((foo)target).goo();
Run Code Online (Sandbox Code Playgroud)