简体   繁体   English

如何在Java中检查以下instanceof?

[英]How do I check for the following instanceof in Java?

I'm looking for a better way to do the following: 我正在寻找一种更好的方法来执行以下操作:

class Animal {}

class Dog extends Animal
class Cat extends Animal
class Rat extends Animal
class Bat extends Animal
.. 50 such animals

Now I have a list of animals - List<Animal> . 现在,我有了动物List<Animal>

I want to do something like this: 我想做这样的事情:

for (Animal animal : animalList) {
   if (animal instanceof (Dog or Cat or 1 of 10 such animals) ) {
      //do something with animal.
   }
}

What is a good way to check wither this animal is an instance of a sublist if animals besides doing 10 instanceof checks? 如果动物除了进行10次instanceof检查外,有什么好的方法来检查该动物是否为子列表的实例?

The direct approach would be: 直接方法是:

for (Animal animal : animalList) {
   for (Class clz : myClassSubList) {
      if (clz.isInstance(animal)) {
         //do something with animal.
         break;
      }
   }
}

edited: as per @shmosel's comment 编辑:根据@shmosel的评论

Expanding on Rogue's comment: 扩展对Rogue的评论:

Have Animal methods to differentiate subclasses like for example Animal.isMammal() or Animal.hasFourLegs() 使用Animal方法来区Animal.isMammal()类,例如Animal.isMammal()Animal.hasFourLegs()

Then the subclasses have properties like Dog.isMammal = true or Bat.hasFourLegs = false 然后,子类具有属性,如Dog.isMammal = trueBat.hasFourLegs = false

abstract class AnimalSubgroup extends Animal
class Dog extends AnimalSubgroup
class Cat extends AnimalSubgroup
if (animal instanceof AnimalSubgroup) {
    // do thing
}

Another advantage of this approach is if there are common properties or methods that these animals should share, they can go in the abstract class. 这种方法的另一个优点是,如果这些动物具有共同的属性或方法,则可以将它们放入抽象类中。

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

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