开发者

Dynamic generation of arrays

I need to generate my array according to 开发者_JAVA百科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?


You could use a Map:

//Build Data-Map
Map<String, Processor[]> processorTypes = new HashMap<String, Processor[]>();
processorTypes.put("first", new Processor[] {new object_a(),object_b(2,3),object_c()});
processorTypes.put("second", new Processor[] {new object_e(),object_f(3),object_g("fdf")});

//Get setup
String userAnswer = getByUser();
Processor[] processors = processorTypes.get(userAnswer);


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:

<processor-config name="first">
    <object type="a"/>
    <object type="b">
        <argument value="2">
        <argument value="3">
    </object>
    <object type="c"/>
</processor-config>

Have a ProcessorConfig class in java that holds all this data and that exposes a method like this:

public Processor[] createProcessors() {
    Processor[] processors = new Processor[objectList.size()];
    for (int i = 0; i < objectList.size(); i++) {
        processors[i] = objectList.get(i).createProcessor();
    }
}

The objectList here is a list of some ObjectWrapper beans holding the data for an object configuration (corresponding to the XML object 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:

configMap.get(userInputString).createProcessors()

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.


I don't think an if-statement would be too bad in this scenario. You could use a ternary operator though:

processors = userChoice
        ? new Processor[] { new object_a(), object_b(2,3), object_c() }
        : new Processor[] { new object_e(), object_f(3),   object_g("fdf") };

Or, if you want more fine-grained control you could do

Processor[] chosenProcessors = (new ArrayList<Processor>() {{

    if (option1) add(new object_a());
    ...
    if (optionN) add(new object_N());

}}).toArray(new Processor[0]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜