我如何知道泛型是Java中的一个类的实例? [英] How do I find out if generic is instanceof a class in Java?
问题描述
public class Vehicle
{
}
公共类车辆延伸车辆
{
}
公共类飞机延伸车辆
{
}
现在,我试图循环列出可以包含汽车和飞机的汽车记录列表。但是,我想弄清楚它是不是飞机记录(而不是汽车记录)。编译器告诉我错误:在检查实例上if(s instanceof Record< Aircraft>)的instanceof非法通用类型。我错过了什么?原谅我,我已经有数年没用过java了。
for(Record<?extends Vehicle> s:rs.getResultReadOnly ))
{
if(s instanceof Record< Aircraft>)
{
...
}
}
由于 type erasure :通用信息 然而你可以这样做: I have the following classes/sub-classes defined. 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.
You can't do this type of check because of type erasure: The generic information However you can do something like this:
这篇关于我如何知道泛型是Java中的一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!< Aircraft> $ c $
if(s.getVehicle()instanceof Aircraft){
}
public class Vehicle
{
}
public class Car extends Vehicle
{
}
public class Aircraft extends Vehicle
{
}
for (Record<? extends Vehicle> s : rs.getResultReadOnly())
{
if(s instanceof Record<Aircraft>)
{
...
}
}
<Aircraft>
will be lost at runtime.if (s.getVehicle() instanceof Aircraft) {
..
}