In my code there are 3 custom classes
CheckinTemplate
Employee
Status
While there was one scenario came that an Object o
, can be possibly any of above class's list. And I want to compare as follow and do certain logic but an error came "Illegal generic type for instanceof"
if (o instanceof List<CheckinTemplate>) {
} else if (o instanceof List<Employee>) {
} else if (o instanceof List<Status>) {
}
This can't be done, since instanceof
is evaluated in runtime, but generic type parameters are erased during compilation. This means that in runtime there is no difference between List<CheckinTemplate>
and List<Employee>
.
You can check whether o instanceof List
(or o instanceof List<?>
if you want to avoid using a raw List
type). If it is, you can cast it to List
(or List<?>
) and then run instanceof
on its elements to determine their type.
if (o instanceof List) {
List list = (List) o;
for (Object e : list) {
if (e instanceof CheckinTemplate) {
} else if (e instanceof Employee) {
} else if (e instanceof Status) {
}
}
}
Java Language Specification states:
15.20.2. Type Comparison Operator instanceof:
is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reference type that is reifiable (§4.7)
and 4.7. Reifiable Types
...
A type is reifiable if and only if one of the following holds:
- It refers to a non-generic class or interface type declaration
- It is a parameterized type in which all type arguments are unbounded wildcards
- It is a raw type
- ...
This is understandable because of 4.6. Type Erasure, that is, at compile time type information is lost and not put into the compiled class file. At runtime there is no type information available to the virtual machine to check what type the List is, so it cannot be checked by instanceof
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With