aspose file tools*
The moose likes Java in General and the fly likes modifying enums Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "modifying enums" Watch "modifying enums" New topic
Author

modifying enums

Hengki Widjaja
Ranch Hand

Joined: Oct 31, 2011
Posts: 44
I have an enum like this:



and I have a file containing specification like this:



What should I do so that when I do System.out.println(Color.Blue); it will produce "This is blue". And I certainly don't want to make toString() functions for every value because I'm going to have lots of enums. It's assured that every enum value will have a counterpart in the file with exact same name (case-sensitive). thanks
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
Probably this is how you should do
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19544
    
  16

Use a java.util.Properties object. You can use it to read your file, and also to map the names. If you use it in a utility class you can then simply use that utility class wherever you need to get the label for an enum:
You then use EnumLabels.getLabel(e) instead of e.toString().


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19544
    
  16

Harsha Smith wrote:Probably this is how you should do

Except a) the labels are not fixed but are stored in a file, so you can't hard code them, and b) Hengki stressed that he does not want to override toString().
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4240
    
    7

Here's one approach. The first thing you can do is give your enums a member variable containing the description. Here's an example that hard-codes them instead of loading from a file:

Then you could probably add a static initializer block (or maybe something in the constructor, or a bit of both) to load the names from a file. You'd want to factor the working out into another class to minimise the additional plumbing you need to add to each enum.
Hengki Widjaja
Ranch Hand

Joined: Oct 31, 2011
Posts: 44
Thanks guys. It worked. Have a nice day to you all!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: modifying enums
 
Similar Threads
Enum Question
Enumerated type toString()
Tiger enums....
switch on a string?
How to insert enum type entity in MySQL with JPA