views:

1031

answers:

4

I want to output some braces in a java MessageFormat. For example I know the following does not work:

MessageFormat.format("  public {0} get{1}() {return {2};}\n\n", type, upperCamel, lowerCamel);

Is there a way of escaping the braces surrounding "return {2}"?

+6  A: 

You can put them inside single quotes e.g.

'{'return {2};'}'

See here for more details.

Brian Agnew
+1 i thought it was \ but ' is the correct one
Markus Lausberg
+1  A: 

Use single quotes:

MessageFormat.format("  public {0} get{1}() '{'return {2};'}'\n\n",
                     type, upperCamel, lowerCamel);

If you want to actualyl use a single quote, just double it. The JavaDoc for MessageFormat gives this somewhat complicated example:

Thus, a string that should result in the formatted message "'{0}'" can be written as "'''{'0}''" or "'''{0}'''".

This is '' for a single quote, then '{' for an escaped brace, then 0, '}' for the closing brace and '' for the closing quote.

Jon Skeet
+2  A: 

Wow. Surprise! The documentation for MessageFormat knows the answer:

Within a String, "''" represents a single quote. A QuotedString can contain arbitrary characters except single quotes; the surrounding single quotes are removed. An UnquotedString can contain arbitrary characters except single quotes and left curly brackets. Thus, a string that should result in the formatted message "'{0}'" can be written as "'''{'0}''" or "'''{0}'''".

Bombe
A: 

String sql = "select * from app_Main where primary_Key = upper(\''{0}\'')"; Object [] replacable = {new Integer(0)};

System.out.println(MessageFormat.format(sql, replacable)+"\n");

Use this one, will definitely help.

Thanks

prabhat(India)

Prabhat Kumar Singh