开发者

how to read properties from GWT host page?

What's the best way to read properties from the GWT host page?

I'm trying to find a simple way to embed properties into the host page and access them from Java.

It seems like Dictionary is the recommended way to go, but it's somewhat fragile in that your dictionary must exist in the host page, or it errors with MissingResourceException. Similarly, Dictionary.get() will throw a resource error if the key you request does not exist.

I'm writing a library, and I'd prefer a more robust solution that won't error out if the user doesn't specify the dictionary or key. Should I just catch exceptions thrown by the Dictionary and return null? Is there a more robust way to do this?开发者_运维知识库

EDIT: at the moment, I'm using the following:

protected Dictionary dict;

public ClientConfiguration(String configName)
{
    try
    {
        dict = Dictionary.getDictionary(configName);
    } catch (MissingResourceException e)
    {
        dict = null;
    }
}

public String getString(String key)
{
    return dict == null ? null : dict.keySet().contains(key) ? dict.get(key) : null;
}


I would say, your solution is very robust already. It's absolutely ok to catch - without rethrowing -

  • a specific Exception (MissingResourceException)
  • which you expect to occur (the resource could be missing),
  • and which will only occur under the circumstances you expect (it would be bad to catch a NullPointerException, because there can be many reasons for that Exception).

You could even change your getString() method a little bit:

public String getString(String key) {
  try {
    return dict == null ? null : dict.get(key);  

  } catch (MissingResourceException e) {
    return null;
  }
}

This should make the method almost twice as fast, because you save the extra call to dict.keySet().contains(key), which takes approximately as long as dict.get(key).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜