我有一個String屬性,涉及到調用一個特定的方法。如何使用字符串調用GWT ClientBundle接口的方法?
我有這樣的DTO,與圖標屬性
public class MyDto
{
String icon; // "first", "second", "third" etc
public String getIcon()
{
return icon;
}
}
在我的界面我有以下方法:(GWT ClientBundle)
public interface MyClientBundle extends ClientBundle
{
@Source("icon_first.jpg")
ImageResource icon_first();
@Source("logo_second.jpg")
ImageResource icon_second();
@Source("icon_third.jpg")
ImageResource icon_third();
}
我目前使用與選擇語句的查詢效率低,但想通過建立一個字符串來選擇正確的方法:
public ImageResource getValue(MyDto object)
{
return getIconFromCode(object.getIcon());
}
private ImageResource getIconFromCode(String code)
{
if(code.equalsIgnoreCase("first"))
{
return resources.icon_first();
}
else if(code.equalsIgnoreCase("second"))
{
return resources.icon_second();
}
else if(code.equalsIgnoreCase("third"))
{
return resources.icon_third();
}
else
{
return resources.icon_default();
}
}
I wan噸建立一個字符串來選擇正確的方法,而不是像"icon_" + object.getIcon()+ "()"
做了一些研究,我明白我需要使用反射?這將如何完成?
你在用什麼?反思有點複雜,可能不是你想要的,我猜測。您可以使用數組,ArrayList或HashMap來快速訪問。一個數組和ArrayList會讓你通過int索引查找,而HashMap會讓你通過任何鍵索引,包括一個int索引。然後,在MyClientBundle中,您可以創建一個getter方法,該方法接受一個鍵/索引參數並返回關聯的ImageResource。 – stoooops
ClientBundle是一個GWT接口,它創建一個具體的類,其中每個方法映射到特定的圖像。我想每次渲染正確的圖像,但我不想要一個具有20個左右元素的開關(或者說是 - else)。 – slugmandrew
我不認爲我可以添加一個方法到MyClientBundle,因爲它是一個接口,實際的類是由代碼生成器創建的。無論如何,由於GWT模擬器不支持反射,我仍然是個笨拙的人。任何建議歡迎:) – slugmandrew