While GWT is not emulate all java's core, what can be used as alternative for:
String.format("The answer is - %d", 42)?
What is the ellegant and efficient pattern to inject arguments to message in GWT?
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
String startTime = "08/11/2008 00:00"; // This could be MM/dd/yyyy, you original value is ambiguous SimpleDateFormat input = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date dateValue = input. parse(startTime);
String. format returns a new String, while System. out. printf just displays the newly formatted String to System.
One elegant solution is using SafeHtml templates. You can define multiple such templates in an interface like:
public interface MyTemplates extends SafeHtmlTemplates { @Template("The answer is - {0}") SafeHtml answer(int value); @Template("...") ... }
And then use them:
public static final MyTemplates TEMPLATES = GWT.create(MyTemplates.class); ... Label label = new Label(TEMPLATES.answer(42));
While this is a little bit more work to set up, it has the enormous advantage that arguments are automatically HTML-escaped. For more info, see https://developers.google.com/web-toolkit/doc/latest/DevGuideSecuritySafeHtml
If you want to go one step further, and internationalize your messages, then see also https://developers.google.com/web-toolkit/doc/latest/DevGuideI18nMessages#SafeHtmlMessages
You can simply write your own format function
instead of doing brain storm.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With