How to create enum dynamically?

后端 未结 4 546
感情败类
感情败类 2021-01-17 09:47

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          


        
相关标签:
4条回答
  • 2021-01-17 10:07

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

    0 讨论(0)
  • 2021-01-17 10:09

    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.

    0 讨论(0)
  • 2021-01-17 10:11

    It's not clear if you want to generate source code or not. I guess not, since even compiled no code in the same program could access the the enum objects except through reflection.

    So why not mapping the table to a ColorEntity object using JPA? You can then have a list or a map of these entities or whatever you need.

    0 讨论(0)
  • 2021-01-17 10:29

    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.

    0 讨论(0)
提交回复
热议问题