java 检查父类是否是子类的实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28617697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:54:03  来源:igfitidea点击:

Check if parent class is instance of child class

java

提问by user3339562

I have one class defined like this:

我有一个这样定义的类:

class Car {

}

And many other defined like this:

还有许多其他定义如下:

class Audi extends Car {

}

class Seat extends Car {

}

class Mercedes extends Car {

}

class Opel extends Car {

}

...

I have a situation where I receive a list of all these cars which is defined like this:

我有一种情况,我收到了所有这些汽车的列表,其定义如下:

List<Car> cars = new ArrayList<Car>();

In that list there are many different cars so how can I find out which one is Audi, which one is Seat etc?

在该列表中有许多不同的汽车,那么我如何才能找出哪一款是奥迪,哪一款是 Seat 等?

I've tried to do this for cars for which I know they are of type Audi:

我已经尝试为我知道它们属于奥迪类型的汽车执行此操作:

Audi audi = (Audi) cars.get(0);

This throws ClassCastException. How to handle this situation?

这抛出ClassCastException. 如何处理这种情况?

回答by Jesper

You can use instanceof:

您可以使用instanceof

Car car = cars.get(0);
if (car instanceof Audi) {
    // It's an Audi, now you can safely cast it
    Audi audi = (Audi) car;
    // ...do whatever needs to be done with the Audi
}

However, in practice you should use instanceofsparingly - it goes against object oriented programming principles. See, for example: Is This Use of the "instanceof" Operator Considered Bad Design?

然而,在实践中你应该instanceof谨慎使用——它违背了面向对象的编程原则。例如,请参阅:“instanceof”运算符的这种使用是否被认为是糟糕的设计?

回答by Tobias

Obvious or not, this will do the trick:

无论是否明显,这都可以解决问题:

Car car = cars.get(0);
if(car instanceof Audi) {
  Audi audi = (Audi) car;
}

回答by Peter Pei Guo

Check with instanceof, for example:

使用 instanceof 检查,例如:

car instanceof Audi

This returns true if variable car is an instance of Audi, otherwise returns false.

如果变量 car 是 Audi 的实例,则返回 true,否则返回 false。

回答by Dmytro

You can use instanceofbefore casting. For example:

您可以instanceof在铸造前使用。例如:

Car someCar = cars.get(0);
Audi audi = null;
if(someCar instanceof Audi){
audi = (Audi) someCar;
}
if(audi != null){
//...

But likely it's a bad idea, because generics was introduced to avoid using casting and instanceof.

但这可能是一个坏主意,因为引入泛型是为了避免使用强制转换和instanceof.