bsh152s
bsh152s

Reputation: 3218

How do I find out if generic is instanceof a class in Java?

I have the following classes/sub-classes defined.

public class Vehicle
{
}

public class Car extends Vehicle
{
}

public class Aircraft extends Vehicle
{
}

Now, I'm trying to loop through a list of vehicle records where the list can contain cars and aircraft. But, I'd like to figure out if it's an aircraft record (and not a car record). The compiler is telling me "error: illegal generic type for instanceof if(s instanceof Record<Aircraft>)" on the instance of check. What am I missing? Forgive me, I haven't used java in years.

        for (Record<? extends Vehicle> s : rs.getResultReadOnly())
        {                    
            if(s instanceof Record<Aircraft>) 
            {
               ...
            }                    
        }

Upvotes: 0

Views: 197

Answers (1)

micha
micha

Reputation: 49572

You can't do this type of check because of type erasure: The generic information <Aircraft> will be lost at runtime.

However you can do something like this:

if (s.getVehicle() instanceof Aircraft) { 
  ..
}

Upvotes: 4

Related Questions