Summary
Override and provide an implementation for the toString() method for the java.text.Format subclasses.
Problem
Code that currently prints an instance of these Format subclasses can benefit from implementing toString() so that an informative representation is returned rather than the default hexadecimal representation of the hash code. This is also beneficial for developers during debugging.
Solution
Override and provide an implementation of toString()
for the Format subclasses.
The value returned by toString() for these subclasses is the locale value (if the subclass is localized), followed by any relevant patterns. For classes that implement toPattern()
, that value is used, otherwise other relevant methods are used to generate patterns. As the patterns are generally enough to distinguish between the Format classes, there is no additional hash code value provided.
The specification for all the Format subclasses of toString() follows a general plain template, as not to be depended on and only treated as a debug string.
As the specification does not precisely indicate the value returned by the toString() method, I have attached sample output for the classes.
CompactNumberFormat [locale: "English (United States)", compact patterns: "[, , , {one:0K other:0K}, {one:00K other:00K}, {one:000K other:000K}, {one:0M other:0M}, {one:00M other:00M}, {one:000M other:000M}, {one:0B other:0B}, {one:00B other:00B}, {one:000B other:000B}, {one:0T other:0T}, {one:00T other:00T}, {one:000T other:000T}]", decimal pattern: "#,##0.###"]
DecimalFormat [locale: "English (United States)", pattern: "foo#0.00#baz"]
SimpleDateFormat [locale: "Chinese (China)", pattern: "EEE, MMM d, ''yy"]
ListFormat [locale: "English (United States)", start: "{0}, {1}", middle: "{0}, {1}", end: "{0}, and {1}", two: "{0} and {1}", three: "{0}, {1}, and {2}"]
MessageFormat [locale: "Chinese (China)", pattern: "Foo {0}"]
ChoiceFormat pattern: "0#foo"
Specification
All the Format subclasses follow the same specification template, where FormatSubclass is replaced by the respective class, for example, ChoiceFormat.
+ /**
+ * {@return a string identifying this {@code FormatSubclass}, for debugging}
+ */
+ @Override
+ public String toString() {
- csr of
-
JDK-8321545 Override toString() for Format subclasses
- Resolved
- relates to
-
JDK-8326908 DecimalFormat::toPattern throws OutOfMemoryError when pattern is empty string
- Resolved