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

java enums and the database

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a standard way to get an enum instance based on a non-enum value?

For example, with good old static constants you can have

public class Color {
public static final int RED = 0;
public static final int GREEN = 1;
public static final int BLUE = 2;
}

Then later you get some values from a database, pass them around functions, and you can always do a check for "if (c == Color.RED)" and so forth.

If Color was a java enum, would it be possible to get an instance of RED from the int 0 without having to have an explicit mapping (i.e. Map<Integer,Color> idToColor), or even worse looping through all the enum values looking for the one with the specific property?

Thanks in advance,
Yuriy
 
Chris Beckey
Ranch Hand
Posts: 116
Eclipse IDE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since enums are just classes, there are some tricks that may help. But it depends on what you want to store in the database.
If you store strings then valueOf() can be used to find the enum:

If you want to use the ordinal values of the int the you can get to them:

You could also put a simple search in the enum itself:

and then get the enum using something like:

You could also put a field in the enum to use as a mapping.

BTW, you may want to be careful about stuffing enum ordinals into a database because a simple code change (ordering in the enum) would result in invalid data with no error indication.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are at least two ways:

Color.values()[0]

and

Color.valueOf("RED");

The first depends on the ordering of the enum constants, the second on the names of the enum constants.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chris and Ilja!

It seems strange that Sun didn't mention the built-in valueOf() method in http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic