javagwtclientbundle

How to call a method of a GWT ClientBundle interface using a string?


I have a String property that relates to calling a particular method.

I have this DTO, with an icon property

public class MyDto
{
    String icon; // "first", "second", "third" etc

    public String getIcon()
    { 
         return icon;
    }
}

In my interface I have these methods: (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();
}

I'm currently using an inefficient lookup with selection statements, but want to select the right method by building a string instead:

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 want to build a string to select the right method instead, something like "icon_" + object.getIcon()+ "()"

Having done some research I understand I need to use reflection? How would this be accomplished?


Solution

  • The interface MyClientBundle should extends ClientBundleWithLookup instead of ClientBundle.

    The ClientBundleWithLookup has a getResource(String name) method that lets you retrieve the resource from the resource name (method name).