java 在运行时(或通过某些中间件编译时)定义枚举的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4619356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:15:02  来源:igfitidea点击:

Simple way to define an enum at runtime (or compile time by some middleware)

javaenums

提问by Hyman

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)?

有没有办法通过从脚本文件(可能是 XML 或 JSON 文件)加载和解析数据来定义一组枚举常量?

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.

我问这个是因为我在一个项目中大量使用枚举,它们有很多参数(比如每个条目也可以有 10-15 个参数),我想给最终用户一种无需修改它们的方法麻烦修改java源代码并重新编译。

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 have to recompile the whole thing.

我认为这不太可能,因为涉及一些静态类型检查,但也许有一种简单的方法可以在编译时预处理文件并使用信息生成静态枚举值。我知道我可以编写一个单独的脚本来完成这项工作并生成一个准备编译的 .java 文件输出,但这意味着用户将不得不重新编译整个事情。

回答by Qix - MONICA WAS MISTREATED

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.

否 - Java 中的原始/内置枚举是静态的,因此它们在编译时进行处理。您需要创建一个动态标签系统(或自制的动态枚举,就像您正在寻找的那样)来实现这种功能。

Best of luck!

祝你好运!

回答by jassuncao

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.

即使可以在运行时向枚举添加新元素,也没有多大意义,因为它们根本不会被使用。毕竟,如果枚举元素在编译时不存在,则意味着您没有编写任何逻辑来处理该元素。

回答by Tim Barrass

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 similarin C# (and this SOquestion). If you're starting from scratch I'd say -- don't rely on enums.

这是基于 C#,所以 YMMV。如果您必须重构枚举,您可以创建一个带有静态方法的类,这些方法复制现有的枚举设置,并从动态加载并使用单独方法访问的字典中获取新设置。我在 C# 中做过类似的事情(以及这个SO问题)。如果你从头开始,我会说——不要依赖枚举。