MessageFormat
可能是你在找什麼:
final MessageFormat format = new MessageFormat("Hi {0}, you are {1, number, #} years old today!");
final String expanded = format.format(new Object[]{person.getName(), person.getAge()});
還有像String.format
一個C:
final String expanded = String.format("Hi %1s, you are %2s years old today!", person.getName(), person.getAge());
測試:
public static void main(String[] args) {
final MessageFormat format = new MessageFormat("Hi {0}, you are {1,number,#} years old today!");
System.out.println(format.format(new Object[]{"Name", 15}));
System.out.println(String.format("Hi %1s, you are %2s years old today!", "Name", 15));
}
輸出:
Hi Name, you are 15 years old today!
Hi Name, you are 15 years old today!
+1感謝您的答覆,但我想在POJO通過,因爲該字符串可能是動態的,這就是爲什麼我不使用你列出的任何方法。 – 2013-03-07 18:27:24
什麼是所有'最後'? – 2013-03-07 20:41:25
我喜歡它們,我認爲它們使代碼更加明顯。看看Rober Simmons Jr.的[Hardcore Java](http://shop.oreilly.com/product/9780596005689.do)。 – 2013-03-07 20:43:41