Correct format string for String.format or similar

后端 未结 4 927
梦如初夏
梦如初夏 2021-02-05 01:21

I\'m sure I\'ve seen String.format used like this before:

String.format(\"Some {1}, {2}, {3}\", var1, var2, var3);

Does this ring

4条回答
  •  感动是毒
    2021-02-05 01:52

    I do not like to specify both index of parameter or its type - mainly when throwing exception and preparing message for it. I like way SLF4j does it. So I wrapped org.slf4j.helpers.MessageFormatter like this:

    public static String subst(String string, Object...objects) {
        return MessageFormatter.arrayFormat(string, objects).getMessage();
    }
    

    Then you can use it like this:

    public void main(String[] args) {
        throw new RuntimeException(MyUtils.subst("Problem with A={} and B={}!", a, b));
    }
    

提交回复
热议问题