When checking for a instance of the current class, why doesn't "x instanceof getClass()" work?

I have an abstract class AssociativeFunction which extends Expr. There are different functions which are subclasses of AssociativeFunction, and there are other expressions which are subclasses of Expr but not AssociativeFunction.

In a method within the AssociativeFunction class, I need to check if an Expr object is an instance of the current class or one of its subclasses,

i.e. Product (extends AssociativeFunction) and inherits this method; therefore, the check should return true for all Product objects and all CrossProduct (extends Product) objects, but false for all Sum (extends AssociativeFunction) and Number (extends Expr) objects.

  1. Why does the following not work? How can I get this to work using the instanceof operator? If I can't, why not?

    if (newArgs.get(i) instanceof getClass()) {
    

    Eclipse yields the error:

    Syntax error on token "instanceof", == expected )

  2. This code seems to work, is that correct? Why is it different than (1)?

    if (getClass().isInstance(newArgs.get(i))) {
    
Jon Skeet
people
quotationmark

Why does the following not work?

Because instanceof requires a type name as the second operand at compile-time, basically. You won't be able to use the instanceof operator.

The production for the instanceof operator is:

RelationalExpression instanceof ReferenceType

where ReferenceType is a ClassOrInterfaceType, TypeVariable or ArrayType... in other words, a type name rather than an expression which evaluates to a Class<?> reference. What you're doing is a bit like trying to declare a variable whose type is "the current class" - the language just isn't defined that way.

This code seems to work, is that correct?

Yes.

Why is it different than (1)?

Because it's using the Class.isInstance method, rather than the instanceof operator. They're simply different things. The isInstance method is effectively a more dynamic version.

people

See more on this question at Stackoverflow