雖然GWT沒有效仿所有Java的核心,有什麼可以作爲替代的:GWT中String.format()的替代方法是什麼?
String.format("The answer is - %d", 42)?
什麼是ellegant和高效的模式在GWT注入參數信息?
雖然GWT沒有效仿所有Java的核心,有什麼可以作爲替代的:GWT中String.format()的替代方法是什麼?
String.format("The answer is - %d", 42)?
什麼是ellegant和高效的模式在GWT注入參數信息?
一個優雅的解決方案是使用SafeHtml模板。您可以在等的接口定義多個這樣的模板:
public interface MyTemplates extends SafeHtmlTemplates {
@Template("The answer is - {0}")
SafeHtml answer(int value);
@Template("...")
...
}
,然後用它們:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class);
...
Label label = new Label(TEMPLATES.answer(42));
雖然這是一點點的工作設置,它具有極大的優點,論據自動HTML轉義。欲瞭解更多信息,請參閱https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
如果你想多走一步,和國際化您的消息,則還看https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages
你可以簡單的寫的做頭腦風暴自己format function
代替。
public static String format(final String format, final String... args,String delimiter) {
String[] split = format.split(delimiter);//in your case "%d" as delimeter
final StringBuffer buffer= new StringBuffer();
for (int i= 0; i< split.length - 1; i+= 1) {
buffer.append(split[i]);
buffer.append(args[i]);
}
buffer.append(split[split.length - 1]);
return buffer.toString();
}
因爲大多數(如在99.999%)的消息格式是靜態的,在編譯時已知的,方式GWT接近它是在編譯時來分析它們。
您通常會使用Messages
subinterface來定位消息的能力,但您有時需要SafeHtmlTemplates
。
在0.001%時,模板不會在編譯時,你可以使用JavaScript的sprintf(參見:http://www.diveintojavascript.com/projects/javascript-sprintf)被稱爲:
public static native String format (String format, JsArrayMixed values) /*-{
return vsprintf(format, values);
}-*/;
你可以寫你自己的。
我寫了一個版本,只是字符串(%S)工作:
public static String format(final String format, final Object... args)
{
checkNotNull(format);
checkNotNull(args);
final String pattern = "%s";
int start = 0, last = 0, argsIndex = 0;
final StringBuilder result = new StringBuilder();
while ((start = format.indexOf(pattern, last)) != -1)
{
if (args.length <= argsIndex)
{
throw new IllegalArgumentException("There is more replace patterns than arguments!");
}
result.append(format.substring(last, start));
result.append(args[argsIndex++]);
last = start + pattern.length();
}
if (args.length > argsIndex)
{
throw new IllegalArgumentException("There is more arguments than replace patterns!");
}
result.append(format.substring(last));
return result.toString();
}
我不知道GWT很多,但我工作的一個GWT項目,我需要這個。在嘗試一些替代方案的同時,我發現這是行得通的;
import java.text.MessageFormat;
MessageFormat.format("The answer is - {0}", 42);
我不知道該項目的開發者是否增加了一些特殊的功能來使這項工作或它默認工作。
這是完全錯誤的 – NimChimpsky 2017-04-06 01:59:57
不存在於JRE Emulation Library中,因此它不能用於客戶端代碼 – 2017-11-27 16:44:16
這對我來說只有一次。我目前沒有在GWT項目上工作。 – sedran 2017-11-28 19:54:48
爲什麼不寫等的方法:
String appendAnswer(int result) {
return "The answer is - " + Integer.toString(result);
}
,因爲不管你做什麼就像在你的代碼格式是解決你的問題。
,如果你曾經面臨的問題一樣整數/字節轉換爲十六進制字符串,你應該使用:
Integer.toString(int, 16);
@downvoter感謝對我的post..please利益提供,我可以提高我的comment.so回答。 – 2013-03-17 06:55:12