Question

In continuation to my previous question, I am trying to write a method that goes like this

public <T extends LivingThing> T getData(Class<T> clazz, Object otherParam) {
    if(clazz instanceof Cat) {
        //do something and return a new Cat
    }
}

I get a compiler error "Incompatible conditional operand types" on the if condition. What am I doing wrong? How do I check for class type in my method?

UPDATE

Ok, I made a code change to make use of isAssignableFrom method. Here is a new problem.

public <T extends LivingThing> List<T> getData(Class<T> classType) {
        LivingThingEnum livingThing = LivingThingEnum
                .getLivingThing(classType);
        if (livingThings.keySet().contains(livingThing))
            return livingThings.get(livingThing);
        return null;
    }
private Map<LivingThingEnum,List<? extends LivingThing>> livingThings;

This gives me a type mismatch! - "cannot convert from List to List". Isn't T supposed to be extending LivingThing, then in which case why does the compiler throw an error?

Était-ce utile?

La solution 2

Your method takes a Class<T> clazz not an instance of LivingThing.

Either change your method to:

public <T extends LivingThing> T getData(T livingThing, Object otherParam) {
    if(livingThing instanceof Cat) {
        //do something and return a new Cat
    }
}

Or use the isAssignableFrom method on Class to test with the Class rather than an instance:

if(Cat.class.isAssignableFrom(clazz))

Autres conseils

instanceof operator works on objects, not on classes.

For example if you have variable obj you can write: obj instanceof Cat. In your case you want to check the following: if (Cat.class.isAssignableFrom(clazz))

Try with Class#getName()

public static <T extends LivingThing> T getData(Class<T> clazz, Object otherParam) {
    if (Cat.class.getName().equals(clazz.getName())) {
        System.out.println("cat");
        // do something and return a new Cat
    }
    ...
}

or try with Class#equals()

if (Cat.class.equals(clazz)) {..}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top