具有枚举选择的Messageformat

时间:2018-01-19 13:22:40

标签: java messageformat

我有一个枚举,并将使用类似选项的方式输出MessageFormat的字符串。我该怎么办?

示例:

public enum Style{
   American,
 European}
...
String s = MessageFormat.format(" {0,choice,American#am|European#eu|null#no}",
   Style.American);

1 个答案:

答案 0 :(得分:0)

在没有帮助并且厌倦了搜索解决方案后,我创建了一个可以解决我的问题的方法:

String s = MessageFormat.format(choicestring(" 
{0,choicestring,American#am|European#eu|null#no}",
  Style.American.toString()),Style.American.toString());

 ....

   private static String choicestring(String fmt, LinkedList<Object> s) throws NumberFormatException {
    String fmtFinal = "";
    int start  = 0;
    Pattern pattern = Pattern.compile("\\{(\\d+),choicestring,(.*)}");
    Matcher matcher = pattern.matcher(fmt);
    String valorEncontrado = "";
    while (matcher.find()) {
        String m = matcher.group();
        String valorProcurar = s.get(Integer.valueOf(matcher.group(1))).toString();
        Optional resultado = Arrays.stream(matcher.group(2).split("\\|")).filter(i -> i.startsWith(valorProcurar)).findFirst();
        if (resultado.isPresent()) {
            valorEncontrado = resultado.get().toString().substring(valorProcurar.length());
        }
        fmtFinal += fmt.substring(start,matcher.start())+valorEncontrado;
        start =  matcher.end();
    }
    fmtFinal = fmt.substring(start,fmt.length());
    fmt = fmtFinal;
    return fmt;
}