aspose file tools*
The moose likes Java in General and the fly likes java enums and the database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "java enums and the database" Watch "java enums and the database" New topic
Author

java enums and the database

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
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

Joined: Jun 09, 2006
Posts: 116

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

Joined: Jul 11, 2001
Posts: 14112
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.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
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...
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: java enums and the database