我如何知道泛型是Java中的一个类的实例? [英] How do I find out if generic is instanceof a class in Java?

查看:739
本文介绍了我如何知道泛型是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 :通用信息< Aircraft>

然而你可以这样做:

  if(s.getVehicle()instanceof Aircraft){

}


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

这篇关于我如何知道泛型是Java中的一个类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆