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
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().
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.
Joined: Oct 31, 2011
Thanks guys. It worked. Have a nice day to you all!!!