javagenericsinheritance

Is there any way of imitating OR in Java Generics


EDIT: I changed a bit the example for getting the idea:

Like

 <Integer or Float>

...without having to create a common interface and make a subclass for Integer and Float to implement it

If not, something like this would maybe have more sense and be useful

 <E extends Number> <E = (Integer|Float)>

If ? is a wildcard why should not we allowed to restrict certain types?


Solution

  • In very extreme cases (pre-Java 7 without AutoCloseable), I would have liked to be able to do that, too. E.g.

    <E extends Connection or Statement or ResultSet>
    

    That would've allowed me to call E.close(), no matter what the actual type was. In other words, E would contain the "API intersection" of all supplied types. In this case it would contain close(), and all methods from java.sql.Wrapper and java.lang.Object.

    But unfortunately, you cannot do that. Instead, use method overloading, e.g.

    void close(Connection c);
    void close(Statement s);
    void close(ResultSet r);
    

    Or plain old instanceof

    if (obj instanceof Connection) {
        ((Connection) obj).close();
    }
    else if (obj instanceof Statement) { //...
    

    Or fix your design, as you probably shouldn't have to intersect APIs of arbitrary types anyway