Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java 5 enum - How to display a different value?

 
Dave Mark
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Dave,

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


 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use values() and iterate over them.
 
Dave Mark
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 31
Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic