Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create enum dynamically?

Tags:

java

I need to create an enum based on a table from the database.

DB table MyColors: id/title/value 1/Red/1 2/Green/4

dynamic create

enum MyColors {
    Red=1,
    Green=4;
}
like image 956
Mediator Avatar asked Feb 03 '11 19:02

Mediator


3 Answers

You can dynamically create source code by reading from the database and simply outputting the results in a format conducive to building an enum. However, it is impractical to create an enum at run time. You would be better off with some kind of associative array.

like image 63
TheBuzzSaw Avatar answered Sep 28 '22 10:09

TheBuzzSaw


Actually there is a possibility of dynamically creating enums using reflection: http://niceideas.ch/roller2/badtrash/entry/java_create_enum_instances_dynamically

like image 43
polaretto Avatar answered Sep 28 '22 12:09

polaretto


One option to is to define an XML Schema and the required values as enum and generate the class files, so that we can manage the values outside the source code, however we cannot dynamically generate the enum values from the database.

like image 32
dosakiller Avatar answered Sep 28 '22 10:09

dosakiller