2012-11-05 48 views
0

好吧我理解Java Reflection如何工作。但是我所做的有點不同於反射教程中的內容。現在我想要的是調用一個方法,通過使用反射調用方法返回。通過在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()將返回正在由正被其反射方法返回的方法返回的對象。但似乎它不工作..我調試我的代碼似乎它不會返回任何東西。我做錯了什麼?請告訴我,如果我做錯了

+1

由於類名/構造函數的錯誤,大部分代碼甚至沒有編譯。另外:「writeline」不是「System.out」的一種方法。 在問你的問題之前解決這些錯誤會節省時間給可能(想要)幫助你的人。 –

+0

謝謝我不在我的IDE前面...謝謝 –

+0

我犯了一個錯誤編輯:我寫了'target.Foo();'而不是'target.Goo();',現在我可以'不要改變它。抱歉。 –

回答

5

可能需要將target對象轉換爲foo type

((foo)target).goo(); 
1

爲了調用類的一個變量中的方法,你應該聲明類的變量:

Foo target = (Foo) method.invoke(obj, arr); // And do some casting. 
target.goo(); 
0

那麼,除了在反射缺失投(試驗班),你的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(); 
    } 
} 
相關問題