首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法通过动态类实例化来简化这一过程?

有没有办法通过动态类实例化来简化这一过程?
EN

Stack Overflow用户
提问于 2012-11-21 00:04:39
回答 4查看 78关注 0票数 3

我有几个子类,它们扩展了父类,强制使用统一的构造函数。我有一个队列,它保存了这些类的列表,它必须扩展MergeHeuristic。我目前拥有的代码如下所示:

代码语言:javascript
复制
    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);

有没有什么方法可以简化这个过程来动态实例化这个类,类似于:

代码语言:javascript
复制
heuristic = new heuristicRequest.somethingSpecial();

这将使if语句块变得扁平。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-21 00:36:15

看起来您正在使用队列中的类作为一种标志,以指示要实例化的请求类型。另一种不使用反射的方法是通过使用工厂方法引入枚举来指示请求类型,从而使此标志行为显式:

代码语言:javascript
复制
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;
  }

}

然后,您的客户端代码将变为:

代码语言:javascript
复制
Queue<HeuristicType> _heuristicQueue = ...
HeuristicType heuristicRequest = _heuristicQueue.pop();
MergeHeuristic heuristic = heuristicRequest.newHeuristic(_parent);

使用枚举而不是反射的主要优点是:

  • 您正在显式地说明添加新启发式类型的要求,即必须有一个启发式类,并且您必须能够基于父级对其进行实例化。
  • 您可以在系统中的单个点上看到所有可用的启发式类型。
  • 通过将实例化抽象到工厂方法中,您可以使用替代构造函数签名。
票数 3
EN

Stack Overflow用户

发布于 2012-11-21 00:16:18

您可以使用反射,但它不会使代码更美观。

代码语言:javascript
复制
try {
    Constructor<? extends MergeHeuristic> heuristicConstructor = 
            heuristicRequest.getConstructor(_parent.getClass());
    heuristic = heuristicConstructor.newInstance(_parent);
} catch (Exception ex) {
    // TODO Handle this
}

只有当你计划有很多不同的类时才这样做。如果只有3个,不用担心,你的代码就可以做到这一点。

票数 2
EN

Stack Overflow用户

发布于 2012-11-21 00:13:30

不幸的是,您不能强制一个类具有特定的构造函数或静态方法-这两种方法在您的情况下都非常有用。

由于所有构造函数都采用相同的参数,因此还有另一种使用动态类实例化来简化代码的方法:

代码语言:javascript
复制
Constructor c = heuristicRequest.getConstructor(ParentClass.class).
heuristic = c.newInstance(_parent);

请注意,您的代码不包含_parent的类类型-在代码示例中我将其命名为ParentClass.class -您必须使其适应您的代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13477192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档