简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM