Why can't a "Class" variable be passed to instanceof?

eric2323223 picture eric2323223 · Apr 7, 2010 · Viewed 33.4k times · Source

Why doesn't this code compile?

    public boolean isOf(Class clazz, Object obj){
        if(obj instanceof clazz){
            return true;
        }else{
            return false;
        }
    }

Why I can't pass a class variable to instanceof?

Answer

Robert Munteanu picture Robert Munteanu · Apr 7, 2010

The instanceof operator works on reference types, like Integer, and not on objects, like new Integer(213). You probably want something like

clazz.isInstance(obj)

Side note: your code will be more concise if you write

public boolean isOf(Class clazz, Object obj){
    return clazz.isInstance(obj)
}

Not really sure if you need a method anymore ,though.