Reputation: 1512
I stole the following enum from jenkov, for example purposes..
public enum Level {
HIGH (3, 33, 333),
MEDIUM(2, 22, 222),
LOW (1, 11, 111);
}
So there is few numbers that can lead to same enum type, both 1 and 11 will return LOW. This i already have implimented.
The actual question is, can enum values ( what are those called? like 1, 11, 111 ) be dynamic ? It seems that the list needed here will change over time, and best solution would be to load new lists at startup.
So ideal solution would be something like
public enum Level {
HIGH (listHigh),
MEDIUM(listMedium),
LOW (listLow);
}
These lists would be loaded at startup by @Configuration @Bean
But enums are static, and even with static int array[] = { 1, 2, 3, 4, 5 };
i get illegal forward reference.
I know im omitting lots of code, but the question is pretty simple i think. I can impliment all the other things around this solution, as long as i get some way to dynamicaly load the values for enums.
Please ask for any information i might have missed here, thank you
Upvotes: 2
Views: 1744
Reputation: 43391
I don't know the Spring aspect, but there are generally two ways you could handle this.
One is by having the enum's constructor, which you can write explicitly, look up the configuration options:
public enum Level {
HIGH,
MEDIUM,
LOW;
private final int whatever;
Level() {
this.whatever = someCodeToLoadFromConfig(name());
}
}
The second is to not have these values in the enum at all, but rather keep an EnumMap of the options you want:
public enum Level {
HIGH,
MEDIUM,
LOW,
}
EnumMap<Level, LevelSettings> levels = new EnumMap<>(Level.class);
for (Level level : Level.values()) {
levels.put(level, someCodeToLoadFromConfig(level.name());
}
The second has a major advantage, which is that it's easy to create alternate options for use in unit tests. It's what I would recommend.
Better yet: why use an enum at all? Just include a class Level, and have it specify its name ("Easy", etc) and settings (1, 11, etc). Create a List of these at startup, and there you go. That way, you don't need to hint around for switches to change when you add an Epic level setting.
Upvotes: 4
Reputation: 31
Even if you can do this, you shouldn't. If you need some lists taken from startup properties, better create map with this enum as a key and loaded list as a value. Then place this map in right context and use.
Upvotes: 1