views:

180

answers:

3

Hi, could anyone tell me why this code won't 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?

Thanks in advance.

+7  A: 

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.

Robert Munteanu
I know the code is totally useless, I just want to demonstrate my confusion:)
eric2323223
`Integer` is **not** a class literal. `Integer.class` would be a class literal (see § 15.8.2 of the JLS: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2). The `instanceof` operator takes a "ReferenceType" (a.k.a a type name) as specified § 15.20.2 of the JLS: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2
Joachim Sauer
I'd use `clazz.isInstance(obj)` since the object's already been supplied.
Donal Fellows
@Joachim, corrected, thanks.
Robert Munteanu
@Donal: improved, thanks.
Robert Munteanu
+4  A: 

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 little advantage over clazz.isAssignableFrom(..) since it deals with the case obj==null better.

Eyal Schneider
+4  A: 

Firstly, instanceof requires that the operand on the right is an actual class (e.g. obj instanceof Object or obj instanceof Integer) and not a variable of type Class. Secondly, you have made a fairly common newbie mistake that you really should not do... the following pattern:

if ( conditional_expression ){
    return true;
} else{
    return false;
}

The above can be refactored into:

return conditional_expression;

You should always perform that refactoring, as it eliminates a redundant if...else statement. Similarly, the expression return conditional_expression ? true : false; is refactorable to the same result.

Michael Aaron Safyan