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()
吗?我想将泛型类型绑定为ExceptionA
,ExceptionB
或ExceptionC
或其子类型之一,以便我可以组合catch块。
catch(ExceptionA | ExceptionB | ExceptionC e) {
throw new D(e);
}
像
这样的东西public <T extends ExceptionA | ExceptionB | ExceptionC> D(T e){..}
我知道多个边界中没有|
。
答案 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) { .. }
}