我有以下简单的代码,它依赖于枚举。
public enum Solvers {
ALG1, ALG2
}
public class MyClass{
private final EnumMap<Solvers, List<Solver>> solverInstancesPerSolver;
private final Solvers[] invocationOrder={Solvers.ALG2,Solvers.ALG1};
...
public void run(){
for(Solvers solver : invocationOrder){
List<Solver> solverInstances=solverInstancesPerSolver.get(solver);
if(solver==Solvers.ALG1){
doSomethingSpecial();
}
}
}
}
我想将此代码转换为在运行时工作的代码,在那里我不知道将有哪些求解器的小修道院。不幸的是,Enums不能在运行时构建,甚至不能在构造函数中构建。 一个潜在的解决方案可能是:
public class MyClass{
private final Map<String, List<Solver>> solverInstancesPerSolver;
private final String[] invocationOrder={"ALG2","ALG1"};
public void run(){
for(Solvers solver : invocationOrder){
List<Solver> solverInstances=solverInstancesPerSolver.get(solver);
if(solver.name.equals("ALG1"){
doSomethingSpecial();
}
}
}
}
然而,在我看来,这非常难看。想象一下有一个错字: private final String [] invokationOrder = {“nonExistingAlg”,“ALG1”}; 这将抛出运行时异常。有更清洁的方法吗?