Can I escape braces in a java MessageFormat?
Solution 1
You can put them inside single quotes e.g.
'{'return {2};'}'
See here for more details.
Solution 2
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}'''"
.
Solution 3
Use single quotes:
MessageFormat.format(" public {0} get{1}() '{'return {2};'}'\n\n",
type, upperCamel, lowerCamel);
If you want to actually 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.
Solution 4
System.out.println(MessageFormat.format("I want to see ticks and curly braces around '''{'{0}'}'''", "this"));
Steve Bosman
I learnt to program in BBC Basic on a BBC Model B and later wrote some small shareware applications on an Acorn A3000. I wrote a lot of FORTRAN 77 and Fortran 90 at university. Since then I've mainly coded professionally in Visual Basic, Oracle PL/SQL, Java and Javascript, and I'm currently transitioning to C#. I've dabbled in C and C++ and Ruby on Rails, but currently I'm writing Android applications in my spare time.
Updated on July 05, 2022Comments
-
Steve Bosman about 2 years
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}"?
-
Steve Bosman over 5 yearsI don't see how this is relevant to a Java question
-
rjmunro over 3 yearsIt would be helpful to see what exactly the result of this would be.