Java:将条件移至消息文件

Java类ResourceBundleMessageFormat提供了一个很好的工具集,用于解决Java应用程序内部的本地化消息。 这篇文章提供了一个小示例,说明如何使用ChoiceFormat将与消息相关的简单条件从Java代码移动到消息文件中。 如果您已经知道ChoiceFormat我认为您不会在本文中学到任何新东西。 但是,以我的经验,许多开发人员并不了解这个不错的小功能。

假设我们有一个用户可以在其中评论某些内容的应用程序。 我们希望在应用程序中的某个位置显示一条简单消息,该消息显示某条内容被评论的频率。 我们要根据评论数显示以下消息:

评论数 信息
0 这个元素没有评论
1个 该元素包含一个评论
2+ 该元素包含[numberOfComments]条评论

为了使用Java的ResourceBundleMessageFormat实现此功能,我们可以使用以下代码。

消息文件(例如messages_en.properties ):

comments.no=This element contains no comments
comments.one=This element contains one comment
comments.multiple=This element contains {0} comments

Java代码:

private String resolveMessage(String key, Object... args) {
  String pattern = bundle.getString(key);
  return MessageFormat.format(pattern, args);
}

private String getMessage(int numberOfComments) {
  String message = null;
  if (numberOfComments == 0) {
    message = resolveMessage("comments.no");
  } else if (numberOfComments == 1) {
    message = resolveMessage("comments.one");
  } else {
    message = resolveMessage("comments.multiple", numberOfComments);
  }
  return message;
}

方法resolveMessage()用于使用ResourceBundleMessageFormat将消息密钥解析为实际消息。 为了实现所请求的功能,我们在属性文件中添加了三个消息键。 在getMessage()我们实现了根据传递的numberOfComments变量来决定应使用哪个消息密钥的逻辑。

getMessage()方法产生预期的结果:

getMessage(0)   // "This element contains no comments"
getMessage(1)   // "This element contains one comment"
getMessage(2)   // "This element contains 2 comments"
getMessage(10)  // "This element contains 10 comments"

但是,实际上有一种更简单的方法可以做到这一点。 实际上,我们可以将在getMessage()实现的完整逻辑移到属性文件中。

我们只需要定义一个键:

comments.choice=This element contains {0,choice,0#no comments|1#one comment|1<{0} comments}

使用此消息,我们可以完全删除getMessage()的逻辑:

private String getMessageUsingChoice(int numberOfComments) {
  return resolveMessage("comments.choice", numberOfComments);
}

结果是完全一样的:

getMessageUsingChoice(0)   // "This element contains no comments"
getMessageUsingChoice(1)   // "This element contains one comment"
getMessageUsingChoice(2)   // "This element contains 2 comments"
getMessageUsingChoice(10)  // "This element contains 10 comments"

让我们仔细看看定义的消息:

  • 0,choice –告诉MessageFormat我们要为第一个参数(0)应用ChoiceFormat
  • 0#无注释–表示如果第一个参数为0,我们希望使用消息无注释
  • 1#one注释–如果第一个参数为1,则返回一个注释
  • 1 <{0}条注释–如果第一个参数大于1,则使用子模式{0}条注释

总之,选择提供了一种将简单的消息相关条件从Java代码移到消息文件中的好方法。


翻译自: https://www.javacodegeeks.com/2013/12/java-moving-conditions-into-message-files.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值