• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can a enum class be dynmaically created  RSS feed

 
Jay Ram
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I need a enum object; but the values in the enum may vary dynamically from time to time according to the values in the database.

Can a Enum class be dynamically created? If so, Can you please provide a small example.

Thanks,
Jay.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are libraries out there that can create classes at runtime (CGLIB for example) but I'm not sure an emun is something you would really want to create at runtime. You would need to rewrite your code everytime the database value changed, wouldn't you?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16058
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would not make much sense to dynamically create an enum, because all the other code in your program, which would use the enum, would not know in advance what values the enum has.

So, for this kind of purpose, an enum is not the right solution. An enum is really only suited when you have a fixed set of values.
 
Craig Taylor
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One example in which it might be nice to have an enum is when refactoring code and moving Enum definitions to the database for added flexibility (won't have to recompile all the time).

As an example, I've extended the enum class to support a hasAttribute() behavior and am now going through code modifying to query enumType.hasAttribute() instead of enumType == value.

There are some code points however that will use a static enum - eg: my inprogress enum value.

Still struggling with how to do this however.
 
Campbell Ritchie
Marshal
Posts: 56530
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch, Craig. Hope you'll like it here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!