好吧我理解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()
將返回正在由正被其反射方法返回的方法返回的對象。但似乎它不工作..我調試我的代碼似乎它不會返回任何東西。我做錯了什麼?請告訴我,如果我做錯了
由於類名/構造函數的錯誤,大部分代碼甚至沒有編譯。另外:「writeline」不是「System.out」的一種方法。 在問你的問題之前解決這些錯誤會節省時間給可能(想要)幫助你的人。 –
謝謝我不在我的IDE前面...謝謝 –
我犯了一個錯誤編輯:我寫了'target.Foo();'而不是'target.Goo();',現在我可以'不要改變它。抱歉。 –