• 0
Votes
name

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

        }
    }
}
  • 0
Reply Report