3

是否有可能为 java.text.MessageFormat 定义一种格式来格式化数字而不用 .toString() 对分隔符其他对象进行分组?

我的麻烦是我必须格式化一个我事先不知道的参数,不管它是不是一个数字。如果我只是使用

java.text.MessageFormat.format("The object: {0}",someobject)

通常只是someobject.toString()按我的意愿调用,但是当someobject它实际上是一个数字时1231231,它会返回(在德语语言环境中)The object: 1,231,231,但我想The object: 1231231在这里。格式化

java.text.MessageFormat.format("{0,number,#}",1231231)

返回The object: 1231231,但是当参数不是数字时,这不起作用。有没有办法指定适用于数字和其他对象的格式?

(如果您想知道:不幸的是,更改 MessageFormat 的语言环境不是一种选择,因为它深深地埋在 JBoss 的日志框架中并且无法访问。)

更新:在将 String.valueOf(someobject) 作为参数传递之前调用它确实解决了这个问题,但在我的情况下也是不可行的,因为这个问题发生在记录时,我不想调用可能昂贵的 someobject。 toString() 当日志级别不允许日志消息并且因此永远不会应用 MessageFormat 时。

4

2 回答 2

0
    final String format = MessageFormat.format("The object: {0}", a == null ? null : a.toString());

    System.out.println("format = " + format);
于 2017-01-24T10:50:45.773 回答
0

A variant of Shylock.Gou's answer that would avoid calling someobject.toString() when this isn't actually used because the loglevel is forbidden, one could wrap the object so that toString is called on use only. This still seems somewhat awkward, though.

public Object wrapToString(Object obj) {
    return new Object() {
        /** {@inheritDoc} */
        @Override
        public String toString() {
            return String.valueOf(obj);
        }
    };
}

Then again, one could also pollute the code by wraping the logging statement with a loglevel check - which might or might not be better, depending on taste.

于 2017-01-24T11:32:01.633 回答