• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

modifying enums

 
Hengki Widjaja
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably this is how you should do
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. It worked. Have a nice day to you all!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic