我有一個關於method.invoke()的問題。我構建方法與下面的代碼:使用實際方法參數的字符串方法實現創建的調用
public void exec(String property_name, Object value){
try{
Method method = some_class.getClass().
getMethod("set"+property_name, new Class[] {
value.getClass()
}
);
method.invoke(some_class, value);
}catch(Exception e){
e.printStackTrace();
}
}
我some_class有方法:
public void setA(Test test){
// do something
}
在組A函數的參數是界面,看起來像:
public interface Test{
public void write(String str);
}
當我使用使用TestImpl的第一個示例代碼中的exec()函數執行Test,引發異常,通知該方法在some_class中找不到。但是,當我使用函數exec()與原始類而不是擴展或實現,方法exec()工作正常。
我應該如何處理類的實現方法?
更新與SSCCE的情況下,它是由some1需要:
public class test {
public static void main(String[] args) {
exec("Name", new TestClassImpl());
}
public static void exec(String property_name, Object value){
try{
some_class sc = new some_class();
Method method = sc.getClass().
getMethod("set"+property_name, new Class[] {
value.getClass()
}
);
method.invoke(sc, value);
}catch(Exception e){
e.printStackTrace();
}
}
}
class some_class{
public some_class(){}
public void setName(TestClass test){
System.out.println(test.name());
}
}
interface TestClass{
public String name();
}
class TestClassImpl implements TestClass{
public String name() {
return "sscce";
}
}
在此先感謝, 謝爾蓋。
你有堆棧跟蹤例外?考慮用[SSCCE](http://sscce.org/)更新你的問題,它會幫助人們幫助你。 – Uhlen 2011-02-10 22:51:19