Generating various Java classes based on runtime configuration text

I have a package that can perform several operations with different parameters. Operations and their parameters are presented in the XML configuration file.

There is a separate class that implements each operation. All of these classes extend the abstract Operation class, so once the class is created, it can be treated the same way in code, regardless of the actual operation.

However, I need to create classes. And so far I can see two ways to do it:

  • switch statement:

    Operation operation;
    switch (operationName) {
    case "OperationA":
        operation = new OperationA();
        break;
    case "OperationB":
        operation = new OperationB();
        break;
    default:
        log.error("Invalid operation name: " + operationName);
        return true;
    }
    
          

  • View the runtime for the class name. I've never tested this option, but it looks like something like:

    Operation operation = (Operation)Class.forName(operationName).newinstance();
    
          

The first option seems cumbersome. The second option seems to trust the config too much, although I'm not sure about that.

Perhaps I just need to check that operationName is a member of a predefined set or list that contains all of my operations (or sets possible values ​​in stone in the XML schema and validates the configuration against it) and then use the second option? Or is there something better?

+3


source to share


1 answer


I would rather use the second option.

An example class. (Note that the default constructor is required because it is called by .newInstance (). You can also refer to this question: Can I use Class.newInstance () with constructor arguments? If you want to create a new class and use the constructor with parameters.)

package com.mypackage;

public class SomeObject {

    public SomeObject() {}
}

      



How to create an instance of this class:

try {
    // you need to use the fully qualified name, not just the class name
    SomeObject object = (SomeObject) Class.forName("com.mypackage.SomeObject").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
    // here you can handle incorrect config in your XML file
}

      

You can also have a list of qualified names in another config file or property and check that list before trying to create a class.

+2


source







All Articles