Is there a syntax or workaround to constrain a generic type parameter to any of a range of types?
I am aware that you can constrain a type to be all
While Java has limited support for "intersection types" like T1 & T2
, support for "union types" is scanty.
Generic types with wildcard are actually union types: G extends X>
is the union of all G
where S
is a subtype of X
.
No support for union of arbitrary two types.
Java 7's multi-catch syntax looks like it supports union of arbitrary exception types
catch (IOException|SQLException ex){ .. }
but not really, the type of ex
is a fixed super class, not a union of the two classes.