动态生成数组
我需要根据从用户收集的命令生成数组。
例如
如果用户输入“第一种数组类型” 我的数组将是
processors = new Processor[] {new object_a(),object_b(2,3),object_c()};
如果用户输入“第二数组类型”, else 我的数组将是
processors = new Processor[] {new object_e(),object_f(3),object_g("fdf")};
我不想写一个大的 if-else 结构。
如何根据配置文件和用户输入动态生成数组?
I need to generate my array according to the commands gathered from the user.
For example
if the user give input "first type of array"
my array will be
processors = new Processor[] {new object_a(),object_b(2,3),object_c()};
else if the user give input "second type of array"
my array will be
processors = new Processor[] {new object_e(),object_f(3),object_g("fdf")};
I do not want to write a big if-else structure.
How can I dynamically generate my array according to a config file and user input?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用地图:
You could use a Map:
假设您有一些 XML(或任何格式)的配置文件,并为每个设置和数组元素及其属性设置了一个名称:
在 java 中有一个 ProcessorConfig 类,它保存所有这些数据和公开这样的方法:
这里的
objectList
是一些ObjectWrapper
beans 的列表,这些 bean 保存对象配置的数据(对应于 XMLobject
element):类型和参数,并且还知道如何根据其状态创建处理器。一旦有了这个,您就可以解析 XML 文件并保存
String
-> 的映射。ProcessorConfig
因此,根据用户输入,您可以简单地编写:当然,您应该检查 null 而不是像上面那样调用方法,但我想让它尽可能短。
编辑:如果您可以在项目中使用 Spring IoC 容器并直接将这些 ProcessorConfig 实例定义为映射中的 bean,而不必自己解析 XML,那么这会容易得多。
Assuming you have the config file as some XML (or whatever format) and set up a name for each setup and the array elements with their properties:
Have a
ProcessorConfig
class in java that holds all this data and that exposes a method like this:The
objectList
here is a list of someObjectWrapper
beans holding the data for an object configuration (corresponding to the XMLobject
element): type and arguments and that also knows how to create a processor based on its state.Once you have this, you can parse the XML file and hold a map of
String
->ProcessorConfig
so based on the user input, you can simply write:Of course, you should check for null and not invoke methods like in the above, but I wanted to keep it as short as possible.
EDIT: this would be a lot easier if you can make use of Spring IoC container in your project and simply define these
ProcessorConfig
instances as beans in a map directly, not having to parse the XML yourself.我认为在这种情况下 if 语句不会太糟糕。不过,您可以使用三元运算符:
或者,如果您想要更细粒度的控制,您可以这样做
I don't think an if-statement would be too bad in this scenario. You could use a ternary operator though:
Or, if you want more fine-grained control you could do