简体   繁体   English

我如何确定泛型是否是Java中的类的instanceof?

[英]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. 编译器在检查实例上告诉我“错误:instanceof if(s instanceof Record <Aircraft>)的非法通用类型”。 What am I missing? 我想念什么? Forgive me, I haven't used java in years. 原谅我,我好几年没有使用Java了。

        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. 由于类型擦除,您无法进行这种类型的检查:常规信息<Aircraft>将在运行时丢失。

However you can do something like this: 但是,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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