Is there any way of imitating OR in Java Generics

前端 未结 3 430
暗喜
暗喜 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: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 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:

    
    

    why won't you just say:

    
    

    ? 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:

    
    

    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.

提交回复
热议问题