在MessageFormat的.properties文件中测试null参数

时间:2010-01-18 11:23:57

标签: java resourcebundle messageformat

是否可以使用资源包和MessageFormat获得以下结果?

  • 当我致电getBundle("message.07", "test")以获取"Group test"
  • 当我致电getBundle("message.07", null)以获取"No group selected"

我在互联网上找到的每个例子都是行星,磁盘上有文件等等。

我只需要在资源包的属性文件中检查一个参数是{{1>}(还是不存在)。我希望找到像null这样的null参数的特殊格式。

我用来获取包的方法是:

{0,choice,null#No group selected|notnull#Group {0}}

我也将此方法称为其他包,例如

  • public String getBundle(String key, Object... params) { try { String message = resourceBundle.getString(key); if (params.length == 0) { return message; } else { return MessageFormat.format(message, params); } } catch (Exception e) { return "???"; } } => getBundle("message.08", 1, 2)(始终参数,无需检查"Page 1 of 2"
  • null => getBundle("message.09")(无参数,无需检查"Open file"

我应该在{.1}}的.properties文件中写什么来描述结果?
我现在拥有的是:

null

2 个答案:

答案 0 :(得分:1)

我建议不要尝试更改捆绑功能(即使你有一个封装它的getBundle方法)。

只需在您的代码中执行:

getBundle(param == null? "message.07.null": "message.07", param)

或制作另一种方法:

getBundleOrNull("message.07", param, "message.07.null")

确实

public String getBundleOrNull(String key, value, nullKey) {
   return getBundle(value == null? nullKey: key: value);
}

答案 1 :(得分:0)

您的.properties文件,

message.07=Group {0} 
message.08=Page {0} of {1}
message.09=Open file
message.null = No group selected

然后,您需要更改代码,为params进行明确检查null。如果null那么您可以执行resourceBundle.getString(NULL_MSG)之类的操作。 NULL_MSG将是这个,

private static final String NULL_MSG = "message.null";

所以,现在你的原始方法会变成这样的东西。

public String getBundle(String key, Object... params) {
  String message = null;
  try {
    if (params == null) {
      message = resourceBundle.getString(NULL_MSG);
    } else {
      message = MessageFormat.format(resourceBundle.getString(key), params);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
  return message;
}

调用我的方法,如下所示

getBundle("message.07", "test") // returning 'Group test'
getBundle("message.07", null) // returning 'No group selected'
getBundle("message.08", 1, 2) // returning 'Page 1 of 2'
getBundle("message.08", null) // returning 'No group selected'
getBundle("message.09", new Object[0]) // returning 'Open file'
getBundle("message.09", null) // returning 'No group selected'

现在告诉我问题出在哪里?