2011-02-10 40 views
1

我有一個關於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"; 
} 
} 

在此先感謝, 謝爾蓋。

+1

你有堆棧跟蹤例外?考慮用[SSCCE](http://sscce.org/)更新你的問題,它會幫助人們幫助你。 – Uhlen 2011-02-10 22:51:19

回答

2

問題是new Class[] { value.getClass() }。有了這個,您可以搜索與參數類型完全相同的類的方法,該方法不存在。

試試這個:

for (PropertyDescriptor prop : Introspector.getBeanInfo(some_class.getClass()).getPropertyDescriptors()) { 
    if (prop.getName().equals(property_name)) { 
    prop.getWriteMethod().invoke(some_class, value) 
    } 
} 

或者只是使用Class.getMethods()和搜索二傳手的名字和一個ARG。

+0

非常感謝!工作很好! – Serhiy 2011-02-10 23:08:49

0

在一般情況下,這並不容易。你進入Java規範的一部分,甚至大部分編譯器都沒有完全正確。

在這種特殊情況下(只有一個參數),基本上必須找到一個方法,其參數類型與給定參數的類型兼容。或者遍歷參數類型的繼承層次結構(不要忘記多個接口!),或者遍歷具有一個參數和所需名稱的類的所有方法,並檢查paramType.isAssignableFrom(argType)。

有一個在春天一個工具類,可能得到它適合大多數情況下:

http://springframework.cvs.sourceforge.net/viewvc/springframework/spring/src/org/springframework/util/MethodInvoker.java?view=markup#l210

(不知道這是否是類的最新版本)

+0

非常感謝您的幫助 – Serhiy 2011-02-10 23:13:46

相關問題