我有几个子类,它们扩展了父类,强制使用统一的构造函数。我有一个队列,它保存了这些类的列表,它必须扩展MergeHeuristic。我目前拥有的代码如下所示:
Class<? extends MergeHeuristic> heuristicRequest = _heuristicQueue.pop();
MergeHeuristic heuristic = null;
if(heuristicRequest == AdjacentMACs.class)
heuristic = new AdjacentMACs(_parent);
if(heuristicRequest == SimilarInterfaceNames.class)
heuristic = new SimilarInterfaceNames(_parent);
if(heuristicRequest == SameMAC.class)
heuristic = new SameMAC(_parent);有没有什么方法可以简化这个过程来动态实例化这个类,类似于:
heuristic = new heuristicRequest.somethingSpecial();这将使if语句块变得扁平。
发布于 2012-11-21 00:36:15
看起来您正在使用队列中的类作为一种标志,以指示要实例化的请求类型。另一种不使用反射的方法是通过使用工厂方法引入枚举来指示请求类型,从而使此标志行为显式:
public enum HeuristicType {
AdjacentMACsHeuristic(AdjacentMACs.class) {
@Override public MergeHeuristic newHeuristic(ParentClass parent) {
return new AdjacentMACs(parent);
}
},
SimilarInterfaceNamesHeuristic(SimilarInterfaceNames.class) {
@Override public MergeHeuristic newHeuristic(ParentClass parent) {
return new SimilarInterfaceNames(parent);
}
},
... // other types here.
;
private final Class<? extends MergeHeuristic> heuristicClass;
public Class<? extends MergeHeuristic> getHeuristicClass() {
return heuristicClass;
}
abstract public MergeHeuristic newHeuristic(ParentClass parent);
private HeuristicType(Class<? extends MergeHeuristic> klass) {
this.heuristicClass = klass;
}
}然后,您的客户端代码将变为:
Queue<HeuristicType> _heuristicQueue = ...
HeuristicType heuristicRequest = _heuristicQueue.pop();
MergeHeuristic heuristic = heuristicRequest.newHeuristic(_parent);使用枚举而不是反射的主要优点是:
发布于 2012-11-21 00:16:18
您可以使用反射,但它不会使代码更美观。
try {
Constructor<? extends MergeHeuristic> heuristicConstructor =
heuristicRequest.getConstructor(_parent.getClass());
heuristic = heuristicConstructor.newInstance(_parent);
} catch (Exception ex) {
// TODO Handle this
}只有当你计划有很多不同的类时才这样做。如果只有3个,不用担心,你的代码就可以做到这一点。
发布于 2012-11-21 00:13:30
不幸的是,您不能强制一个类具有特定的构造函数或静态方法-这两种方法在您的情况下都非常有用。
由于所有构造函数都采用相同的参数,因此还有另一种使用动态类实例化来简化代码的方法:
Constructor c = heuristicRequest.getConstructor(ParentClass.class).
heuristic = c.newInstance(_parent);请注意,您的代码不包含_parent的类类型-在代码示例中我将其命名为ParentClass.class -您必须使其适应您的代码。
https://stackoverflow.com/questions/13477192
复制相似问题