Search code examples
javainstanceofparents

Java intanceof false if have parent


I am creating some sort of Achievement system and I have a class KillXEnemies and then I inherit from it with classes like KillXEnemiesWeapon (enemies killed with an certain weapon). And when you kill an enemy I loop trough the achievement objects and add that an enemy has been killed with:

if(object instanceof KillXEnemies)
    ((KillXEnemies)object).addEnemyKilled();

But then the KillXEnemiesWeapon gets tracked as well because it inherits from KillXEnemies. I know one solution is:

if(object instanceof KillXEnemies && !(object instanceof KillXEnemiesWeapon))
    ((KillXEnemies)object).addEnemyKilled();

But I am about to get quite many classes that inherits from KillXEnemies and it seems to be a bad solution to have like 20 !(object instanceof (---))

So I am wondering if there is an easier way to check if the object only is KillXEnemies and not KillXEnemiesWeapon


Solution

  • You can use Object#getClass to get the object's actual class, then compare that to KillXEnemies.class.

    if (object.getClass().equals(KillXEnemies.class))
    

    That will be true of object is a KillXEnemies but not if object is an instance of a subclass of it.

    But I wonder (and recognizing that you have a lot more information to work with than I do, so I could easily be wrong) if classes and subclasses are the best way to model this information...