Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make java enum elements configurable

Tags:

java

enums

spring

hello guys i'm not sure if the title is descriptive enough.what i mean is creating an enum like so

public enum Test{
  ONE, TWO ,THREE
}

this looks like hard coded.if for some reason i need to add the FOUR some certain business rules evolution reasons.should i code it and deploy it again? isn't a way to let it pick the elements from a file , spring config for example or property file? THanks for reading.

like image 731
black sensei Avatar asked Jun 13 '26 19:06

black sensei


2 Answers

If the enum value doesn't explicitly exist in code, how could you ever use it? Test.Four would not compile. Any code which could somehow reference Test.Four would be invalid and would crash, until the point in time when the file is read and the new values are added.

You can, of course, use arrays or collections of values and manipulate those at runtime - load them from a file or from the database or whatever - but not enums.

like image 56
Rex M Avatar answered Jun 15 '26 10:06

Rex M


I asked a similar question here. The content may be of interest.

The concensus seemed to be that Java's enum type is static by design. If you need something that can be altered at runtime, you should ideally use a different data structure.

The less preferred ideas were along the lines of extending Enum, etc.

like image 33
brabster Avatar answered Jun 15 '26 11:06

brabster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!