Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate an enum with values from database

I have a table which maps String->Integer.

Rather than create an enum statically, I want to populate the enum with values from a database. Is this possible ?

So, rather than delcaring this statically:

public enum Size { SMALL(0), MEDIUM(1), LARGE(2), SUPERSIZE(3) }; 

I want to create this enum dynamically since the numbers {0,1,2,3} are basically random (because they are autogenerated by the database's AUTOINCREMENT column).

like image 437
Jacques René Mesrine Avatar asked May 12 '09 06:05

Jacques René Mesrine


People also ask

Can you assign values to enums?

Enum ValuesYou can assign different values to enum member. A change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member.

Can we use .equals for enum?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Does enum inherit from object?

Inheritance Is Not Allowed for Enums.

Can enum be parameterized?

Enums can be parameterized.


1 Answers

No. Enums are always fixed at compile-time. The only way you could do this would be to dyamically generate the relevant bytecode.

Having said that, you should probably work out which aspects of an enum you're actually interested in. Presumably you weren't wanting to use a switch statement over them, as that would mean static code and you don't know the values statically... likewise any other references in the code.

If you really just want a map from String to Integer, you can just use a Map<String, Integer> which you populate at execution time, and you're done. If you want the EnumSet features, they would be somewhat trickier to reproduce with the same efficiency, but it may be feasible with some effort.

So, before going any further in terms of thinking about implementation, I suggest you work out what your real requirements are.

(EDIT: I've been assuming that this enum is fully dynamic, i.e. that you don't know the names or even how many values there are. If the set of names is fixed and you only need to fetch the ID from the database, that's a very different matter - see Andreas' answer.)

like image 67
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet