eric2323223 eric2323223 - 1 year ago 56
Java Question

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

could anyone tell me why this code won't compile?

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

Why I can't pass a class variable to

Thanks in advance.

Answer Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download