Is there a way to simulate OR in Java Generics

EDIT: I changed the example a bit to get the idea:

how

 <Integer or Float>

... without the need for a common interface and subclass for Integer and Float to implement it

If not, something like this might make more sense and be useful

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

If? is a wildcard, why shouldn't we restrict certain types?

+5
source share
3 answers

This is impossible, and I almost do not see any value in it. You use generics to limit the type, for example. in collections. With the help of the operator, oryou know as much about the type as you know about the most specific supertype of both of them, Objectin this case. So why not just use it Object?

:

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

list.get(0)? String Number? . String, Number - ... Object.

. :

<Integer or Float>

:

<Number>

? , Number , floatValue() intValue(). ?


, and:

<E extends Serializable & Closeable>

- E, Serializable, Closeable. , E Serializable, Closeable. . : Java Generics .

+11

(pre-Java 7 AutoCloseable), . .

<E extends Connection or Statement or ResultSet>

E.close(), , . , E " API" . close(), java.sql.Wrapper java.lang.Object.

, , . , .

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

instanceof

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

, , , API

+5

I do not see any real use in this ... But in any case, I believe that the closest to it are added common interfaces for possible implementations.

+1
source

All Articles