Java:"best practices" 控制在执行时调用哪些 class 构造函数的方法是什么?

Java: what is "best practices" way of controlling what class constructors to call at execution?

我正在尝试修改下面的块,需要弄清楚 "the right way" 才能做到:

PRQ prq = new PRQ();
XYZ1 xyz1 = new XYZ1();
XYZ2 xyz2 = new XYZ2();

features = new ArrayList<MyFeature>();

// START OF MAIN BLOCK
// This is rigid: need to comment out lines and rebuild to exclude features
// Want to control this at execution time by a config file
//
features.add(new ABCFeatures());
features.add(new PRQFeatures(prq));
features.add(new XYZFeatures(xyz1,xyz2));
// ...
// END OF MAIN BLOCK

public class ABCFeatures extends MyFeature {
    public ABCFeatures()
    {
    }
}

public class PRQFeatures extends MyFeature {
    public PRQFeatures(final PRQ prq)
    {
    }
}

public class XYZFeatures extends MyFeature {
    public XYZFeatures(final XYZ1 xyz1,final XYZ2 xyz2)
    {
    }
}

因此,对于输入数据的每个标记,我都计算了一堆异构特征。其中一些需要资源来计算,并且在实例化时提供(prqxyz1xyz2)。

现在如果我想通过 运行 我的代码进行试验并关闭一些功能,我需要注释掉相应的 features.add(new ... 行,重建 jar 然后重新运行。太死板了!我想在执行时使用某种类型的配置文件来控制它,该文件说明哪些功能打开,哪些关闭。

所以 2 个问题:

  1. 看起来我需要使用 getClass().getDeclaredConstructors(),但我对它应该如何使用有点困惑
  2. 我想与#1 相关:是否有指定配置的首选方法?也就是说,它应该是某种特定格式的 JSON/XML 文件吗? Java 中是否有现成的机器来支持这种情况?

为什么getDeclaredConstructors()?只需将对 features.add(MyFeature) 的调用包装在取决于您的配置文件的 if 语句中。

Properties cfg=new Properties();
cfg.load(new FileInputStream("features.properties"));//current directory, default encoding: take care 
if(cfg.getProperty("USE_ABC").equalsIgnoreCase("true")){
    features.add(new ABCFeatures());
} 
if(cfg.getProperty("USE_PRQ").equalsIgnoreCase("true")){
    features.add(new PRQFeatures(prq));
} 

当然你可以为 属性 名称使用常量,封装检查属性值的函数等。