I have a suite that can run a few operations with different parameters. The operations and their parameters are provided in an XML config file.
There is a separate class implementing each operation. All of these classes extend an abstract Operation class, so once the class is created it can be handled in the same way in the code, whatever the actual operation is.
However, I do need to create the classes. And so far I see two ways of doing it:
a 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;
}
A runtime lookup of a class name. I never tested this option, but it seems to be something like:
Operation operation = (Operation)Class.forName(operationName).newinstance();
The first option seems unwieldy. The second option seems to trust the config too much, though I am not sure about this.
Perhaps I should just verify that operationName is a member of a predefined set or list that contains all my operations (or else set thepossible values in stone in an XML schema and verify the config against it), then use the second option? Or is there something better?
I would prefer to 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 a constructor with parameters.)
package com.mypackage;
public class SomeObject {
public SomeObject() {}
}
How to create an instance of that 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 configuration file or property and check against that list before attempting to create a class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With