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

Use Class<?> parameter in instanceof method

I have the following method that can return different types of Storable (ex: Food, Ore).

Inventory.java

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(cls.isInstance(storable)) {
            this.inventory.remove(storable);
            return storable;
        }
    }
    return null;
}

It works, however I’m forced to cast my result like below:

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

Food food = (Food) inventory.get(Food.class);

With Java 15 and above, we can define casted object directly with instanceof (link to javadoc). I’m wondering if I can use this new syntax and return casted object directly.

I tried this but instanceof keyword only works with type not variable:

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(storable instanceof cls castedItem) {  //cls cannot be resolved to a type
            this.inventory.remove(storable);
            return castedItem;
        }
    }
    return null;
}

>Solution :

Make your method generic:

public <S extends Storable> S get(Class<S> cls) {
    for (Storable storable : inventory) {
        if (cls.isInstance(storable)) {
            this.inventory.remove(storable);
            return cls.cast(storable);
        }
    }
    return null;
}

Note the use of cls.cast. That’s like (S) storable but without the compiler warning.

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