Simple way to define an enum at runtime (or compile time by some middleware)
is there a way to define an enum set of constants by loading and parsing the data from a script file (maybe an XML or a JSON file)?
I ask this because I'm using enums intensively in a project, they have a lot of parameters (like every entry can have also 10-15 parameters) and I would like to give to the final user a way to modify them without having to bother modifying java sources and recompile.
I don't think it is easily possible since there is some static type check involved but maybe there is a simple way to preprocess a file at compile time and use the info to produce the static enum values. I know I could just write a separate script to do this work and produce a .java file output ready to be compiled but this will imply that the user will ha开发者_运维知识库ve to recompile the whole thing.
No - Primitive/built-in Enums in Java are static, so they are processed at compile-time. You would need to create a system of dynamic tags (or home-made dynamic enums, like what you're looking for) to achieve that sort of functionality.
Best of luck!
You can't. Enums are essentially a tool for the programmer while he is developing.
Even if was possible to add new elements to an enum at runtime, it wouldn't make much sense, because they wouldn't be used at all. After all, if an enum element doesn't exist at compile time, it means you didn't wrote any logic to handle that element.
This is based on C#, so YMMV. If you're having to refactor an enum you can create a class with static methods that replicate the existing enum settings, and get new settings from a Dicitonary that's loaded dynamically and is accessed using a separate method. I've done something similar in C# (and this SO question). If you're starting from scratch I'd say -- don't rely on enums.
精彩评论