Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing class to use instanceof in a function

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading