Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 882
eric2323223 Avatar asked Apr 07 '10 07:04

eric2323223


People also ask

Does Instanceof work for superclass?

Yes, it would.

Does Instanceof check for subclasses?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type.

Is a class an Instanceof interface?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

What is Instanceof a class in Java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. Its syntax is. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .


2 Answers

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.

like image 160
Robert Munteanu Avatar answered Oct 21 '22 11:10

Robert Munteanu


instanceof can be used only with explicit class names (stated at compile time). In order to do a runtime check, you should do:

clazz.isInstance(obj)

This has a small advantage over clazz.isAssignableFrom(..) since it deals with the case obj == null better.

like image 42
Eyal Schneider Avatar answered Oct 21 '22 11:10

Eyal Schneider