Is there any way of imitating OR in Java Generics

前端 未结 3 405
暗喜
暗喜 2021-01-11 13:05

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

Like

 

...without having to create a common in

相关标签:
3条回答
  • 2021-01-11 13:22

    I don't see a real use for it... But anyways, I believe the closest you'd get to it is extending common interfaces for the possible implementations.

    0 讨论(0)
  • 2021-01-11 13:23

    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

    0 讨论(0)
  • 2021-01-11 13:30

    It's not possible and I hardly see any value in it. You use generics to restrict type, e.g. in collections. With or operator you know as much about the type as much you know about the most specific supertype of both of them, Object in this case. So why not just use Object?

    Hypothetical:

    List<E extends String or Number> list = //...
    

    What is the type of list.get(0)? Is it String or Number? But you cannot have a variable of such type. It cannot be String, it cannot be Number - it can only be... Object.

    UPDATE: Since you changed your example in question to:

    <Integer or Float>
    

    why won't you just say:

    <Number>
    

    ? Note that Number has methods that allow you to easily extract floatValue() and intValue(). Do you really need the exact type?


    Note that you can use and operator:

    <E extends Serializable & Closeable>
    

    And that makes perfect sense - you can use variable of type E where either Serializable or Closeable is needed. In other words E must extend both Serializable and Closeable. See also: Java Generics Wildcarding With Multiple Classes.

    0 讨论(0)
提交回复
热议问题