检查数组中的元素是否是Java中的SubClass

Lin*_*00b 6 java arrays object

让我们假设我想检查Object数组中的值是否属于超类或子类,例如我的超类叫Called Animal,我声明了一个类型为Animal的数组

Animal myAnimals[] = new Animal[];
Run Code Online (Sandbox Code Playgroud)

现在假设有像Lion,Tiger,Elephant等动物的子类.如果我要遍历数组,我如何区分子类(Lion,Tiger等)和超类Animal?谢谢!

Yas*_*jaj 6

运用 instanceof

在运行时,如果引用可以在不引发ClassCastException的情况下将引用(第15.16节)强制转换为ReferenceType,则instanceof运算符的结果为true.

for (Animal a : myAnimals) {
    if (a instanceof Lion) System.out.println("Lion");
    // etc.
}
Run Code Online (Sandbox Code Playgroud)