接收和返回两种类型之一的函数

时间:2015-03-31 15:54:46

标签: java templates generics

我正在将C ++代码迁移到Java中并遇到以下问题。 我有四个类(转移到Java之后):ABuilt, ABuilder, BBuilt, BBuilder

class ABuilt implements A {
  private BBuilt b;

  public A(BBuilt b) {this.b = b;}
  @Override
  public BBuilt getB() {return b;}
}

class ABuilder implements A, Builder<ABuilt> {
  private BBuilder b;

  @Override
  public getB() {return b;}
  public setB(BBuilder b) {this.b = b;}
  @Override
  public ABuilt build() {return new ABuilt(b.build();}
}

class BBuilt implements B {
  int data;

  public BBuilt(int data) {this.data = data;}
  @Override
  int getData() {return data;}
}

class BBuilder implements B, Builder<BBuilt> {
  int data;

  @Override
  public BBuilt build() {return new BBuilt(data);} 
  public BBuilder(int data) {this.data = data;}
  @Override
  int getData() {return data;}
  void setData(int data) {this.data = data;}
}

我有一个获得A并返回其B的函数。这很简单:

B getB(A a) {return a.getB();} // This works fine.

问题是以下情况:

void setData(ABuilder a, int data) {
  BBuilder b = (BBuilder) getB(a);
  b.setData(data);
}

我想避免演员。我可以通过编写两个函数getBBuilder(ABuilder a), getBBuilt(ABuilt a)来解决这个问题。这不好,因为我要么重复两个函数中的代码,要么不必要地构建a,因为我必须将代码库中的所有用法从getB更改为getBBuilder之一或gtBBuilt(其中有很多,我不知道我是否可以编写脚本)。是否有任何方法可以定义getB,如果BBuilder类型为a,则会返回ABuilder类型,如果BBuilt则返回a是类型ABuilt?在C ++中,typedef ABuilderABuilt类型BType分别定义为BBuilderBBuilt,这很容易。然后按如下方式定义getB

template <class AType>
AType::BType getB(AType a) {return a.getB();}

0 个答案:

没有答案