Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get “Illegal generic type for instanceof” error when coparison

Tags:

java

android

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>) {

}
like image 688
Ebin Joy Avatar asked Sep 15 '25 16:09

Ebin Joy


2 Answers

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) {

        }
    }
}
like image 78
Eran Avatar answered Sep 18 '25 06:09

Eran


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.

like image 20
user85421 Avatar answered Sep 18 '25 07:09

user85421