0

OK、JavaReflectionがどのように機能するかは理解しています。しかし、私がしていることは、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
        }
    }

今、私は自分の経験に大きく依存しており、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 クラスに 1 つのエラーがありました。コードは次のようになります。

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 に答える