Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the alternative for String.format() in GWT?

Tags:

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?

like image 658
Alexandr Belan Avatar asked Mar 16 '13 18:03

Alexandr Belan


People also ask

What is string format () used for?

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.

What is the name of the string format method?

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.

How do you change a string format?

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);

Is string format the same as printf?

String. format returns a new String, while System. out. printf just displays the newly formatted String to System.


2 Answers

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

like image 62
Chris Lercher Avatar answered Oct 02 '22 21:10

Chris Lercher


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();  } 
like image 40
Suresh Atta Avatar answered Oct 02 '22 22:10

Suresh Atta