Home > database >  Passing class to use instanceof in a function
Passing class to use instanceof in a function

Time:05-11

I have a class structure:

class BonusCard{
}

class AddResourceCard extends BonusCard{

}

class AddGoldCard extends BonusCard{

}

Now, I also have a function in which I want to pass AddResourceCard or AddGoldCard and in someones Inventory I want to check if an object in that Inventory is an instance of the class that I put into the function.

private void removeCardFromPlayer(Player player, BonusCard cardToRemove){
    for(BonusCard card : player.getInventory().getBonusCards()){
        if(card instanceof cardToRemove.getClass()){ //this line doesn't work sadly
            player.getInventory().getBonusCards().remove(card);
            break;
        }
    }
}

A function call should look like this:

removeCardFromPlayer(player, AddResourceCard);

or

removeCardFromPlayer(player, AddGoldCard);

There should be an easy straightforward way to accomplish what I'm trying to do, I just don't really know what to search for to be completely honest.

CodePudding user response:

I think what you are looking for is card.getClass().equals(cardToRemove.getClass()).

This compares the classes of the two objects and checks whether they are the same. If you want to regard some hierarchy, you would then probably rather go for isAssignableFrom instead of equals

CodePudding user response:

You probably want to pass the class itself:

private void removeCardFromPlayer(Player player, Class<? extends BonusCard> typeToRemove) {
    for (BonusCard card : player.getInventory().getBonusCards()) {
        if (typeToRemove.isInstance(card)) {
            player.getInventory().getBonusCards().remove(card);
            break;
        }
    }
}

Calls to the method would look like this:

removeCardFromPlayer(player, AddResourceCard.class);
removeCardFromPlayer(player, AddGoldCard.class);

CodePudding user response:

I would add new abstract method boolean canBeRemoved() to the parent class. And override and implement it in the child classes.

Then in the loop, I just will call this method and act accordingly.

  • Related