在Java泛型方法中将上限限制为给定类型之一

时间:2016-04-20 21:42:33

标签: java generics

class ExceptionA extends Error{}
class ExceptionB extends SomeException{}
class ExceptionC extends Exception{}

class D extends Exception {
  public D(ExceptionA a){..}
  public D(ExceptionB b){..}
  public D(ExceptionC c){..}
}

void someMethodSomewhere() {
  try{
    ....
  } catch (ExceptionA a) {
    throw new D(a);
  } catch (ExceptionB b) {
    throw new D(b)
  } catch (ExceptionC c) {
    throw new D(c)
  }
}

在上面的代码段中,我可以生成构造函数D()吗?我想将泛型类型绑定为ExceptionAExceptionBExceptionC或其子类型之一,以便我可以组合catch块。

catch(ExceptionA | ExceptionB | ExceptionC e) {
  throw new D(e);
}

这样的东西
public <T extends ExceptionA | ExceptionB | ExceptionC> D(T e){..}

我知道多个边界中没有|

1 个答案:

答案 0 :(得分:3)

我不确定你是否可以通过这种约束使其“真正”通用。

我能想到的唯一方法是保持三个重载,但那些调用一个私有的,无界的泛型方法:

class Utils {
  public final A add(A a1, A a2){ return addInternal(a1, a2); }
  public final B add(B b1, B b2){ return addInternal(b1, b2); }
  public final C add(C c1, C c2){ return addInternal(c1, c2); }

  private <T> T addInternal(T a1, T a2) { .. }
}