Saravanan M
Saravanan M

Reputation: 4747

Limit upper bound to one of given types in Java generic method

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)
  }
}

In the above snippet, can I generify the constructor D()? I want to bound the generic type to be one of ExceptionA,ExceptionB or ExceptionC or their subtypes so that I can combine the catch blocks.

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

Something like

public <T extends ExceptionA | ExceptionB | ExceptionC> D(T e){..}

I know there is no | in multiple bounds.

Upvotes: 0

Views: 131

Answers (1)

Andy Turner
Andy Turner

Reputation: 140544

I'm not sure that you can make it "really" generic with that constraint.

The only way that I can think is to keep the three overloads, but have those call a private, unbounded generic method:

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) { .. }
}

Upvotes: 3

Related Questions