aspose file tools*
The moose likes Java in General and the fly likes Java 5 enum - How to display a different value? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java 5 enum - How to display a different value?" Watch "Java 5 enum - How to display a different value?" New topic
Author

Java 5 enum - How to display a different value?

Dave Mark
Greenhorn

Joined: Feb 21, 2004
Posts: 19
Hi all,

I have a question about Java 5 enums. I'm trying to have UserState.ACTIVE in my code but have "A" saved to the database. Then when I get "A" from the database I get the enum representing UserState.ACTIVE. We're limited by the User POJO which can't change from using a String.

Here's my code so far...



I use the private method getEnum("A") instead of UserState.valueOf("A") as I get an error saying the value "A" doesn't exist (which I know it doesn't). The thing is, I'll have to modify the private getEnum method everytime a new state is added to the enum.

Is there a better way to code this enum so I can use UserState.valueOf("A") ?
Oscar Costa
Ranch Hand

Joined: Feb 05, 2009
Posts: 31

Hello Dave,

Why not do you use the Data Base values ("A" and "I") in the Enum?



"Do or do not... there is no try!" - Jedi Master Yoda
> SCJP 5 : SCWCD 5 : SCBCD 5 <
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

Use values() and iterate over them.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Dave Mark
Greenhorn

Joined: Feb 21, 2004
Posts: 19
Thanks for the nudge in the right direction Rob. Sorry Oscar, I don't like UserState.L (what does that stand for!?) Some last minute reading and a few ideas later, I came up with the following as Rob suggested...I like my getEnum method so much now I made it public I'm also glad it's now scalable for the future while relaxing the rules for instantiating an instance. I can use either the value or the name (case insensitive) keeping UserState.ACTIVE in the Java code and "A", "I" etc. in the database as per the specification which I'm not allowed to change (the best of both worlds).It's a pity you can't override valueOf but heh, I'll document it. It'll be a lot better using this with Hibernate/JPA rather than going down this road!
Oscar Costa
Ranch Hand

Joined: Feb 05, 2009
Posts: 31

Dave Mark wrote:Sorry Oscar, I don't like UserState.L (what does that stand for!?)


You are correct Dave. Here, we use a framework that use this approach to "easily" use Enums in Hibernate. But is much limited.
Dave Mark
Greenhorn

Joined: Feb 21, 2004
Posts: 19
We have another situation with the group specifying possibly a type of "region", and if it doesn't that's normal too so no exception is to be thrown...

 
Don't get me started about those stupid light bulbs.
 
subject: Java 5 enum - How to display a different value?