简体   繁体   中英

instanceof doesn't seem to work - what's wrong with my code?

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?

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))

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))

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)) {..}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM