簡體   English   中英

使用哈希表值的方法名稱?

[英]Using for a hashtable value the name of a method?

我創建了一個哈希表,該哈希表將保留一個字符串,該字符串將表示用戶將給出的方法的名稱,並且將實際方法調用的值也保留為字符串。 我使用的代碼是這里的代碼:

public void getMethod(String givenMethod){

    Map<String, String> methods = new HashMap<String, String>();
    methods.put("length", "length();");

    methods.get(givenMethod);

}

從主要方法中,我調用objectX.getMethod(“ length”);,但是方法length(); 不執行。 有人能幫助我嗎?

您正在獲取該方法,但未在調用它。 您將必須執行以下操作:

Method yourMethod = objectX.getClass().getDeclaredMethod("yourMethodName"); //This is the string that represents the name of the method.

然后,您調用該方法。 所有這些都是通過反思:

yourMethod.invoke(YourObject);

invoke方法的參數首先是對象,然后是屬性。

您還可以獲得方法的返回類型並強制轉換結果,因為調用該方法將導致對象類型方法:

yourMethod.getReturnType(); //This line gives you the type returned by your method.

使用Java ** reflection按名稱調用方法
(正如您所說的,您將方法名稱存儲在map中)。
有關更多詳細信息,請閱讀以下文章: http : //java.sun.com/developer/technicalArticles/ALT/Reflection/

您需要使用反射來按名稱調用方法。 所以您的數據結構看起來更像

Map<String, Method> meth = new Hashmap<String,Method>();

其中Method是實際對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM