views:

164

answers:

4

In Java is there a way to retrieve the format string from a Format object (or any derived classes)

In code:

Format f = new DecimalFormat("$0.00");
System.out.println(???);

Is there something I can use to get System.out.println(???); to print "$0.00".

I looked at toPattern(); but that function doesn't appear in the abstract Format class and the variable I'm working with can be anything that extends Format.

A: 

No such luck, I'm afraid! You have to know which subclass you're dealing with and call the appropriate method :-(

Brian Agnew
A: 

There is no known direct way to do this from the parent Format. as patterns actually exist at the leaves of the Format hierarchy (SimpleDateFormat, MessageFormat, ChoiceFormat, DecimalFormat); which have toPattern methods. Since it seems to be the convention, you might be able to obtain it by reflection.

MahdeTo
+1  A: 

The pattern (if there is any at all) depends on the subclass of Format. There is no guarantee that a Format would even use a pattern for its formatting.

Edit: I'm not sure what you're trying to do, but if you need to persist a Format instance, it is Serializable.

Steve Kuo
A: 

I am not sure what is access you have to the code but if you apply this small change in the first line you should be able to get the information you are looking in this manner:

DecimalFormat f = new DecimalFormat("$0.00"); 
System.out.println(f.toPattern());
KingInk