Java instanceof with class name

14,754

Solution 1

What is the difference between "Parent" and "Parent.class"?

The latter is a class literal - a way of accessing an object of type Class<Parent>.

The former is just the name of a class, which is used in various situations - when calling static methods, constructors, casting etc.

Does the second 'instanceof' make more sense from the view of strict programming?

Well not as the language is defined - instanceof only works with the name of a type, never an expression. If you could write

if (a instanceof Parent.class)

then I'd expect you do be able to write:

Class<?> clazz = Parent.class;
if (a instanceof clazz)

... and that's just not the way it works. On the other hand, there is the Class.isInstance method which you can call if you want.

What do you mean by "the view of strict programming" in the first place?

Solution 2

Parent is a class, so the second example doesn't make more sense that the first. You're asking if the instance is an instance of the class, a instanceof Parent is a pretty direct expression of that.

Parent.class is an instance of Class, so even if the second example compiled (it doesn't, the right-hand of instanceof can't itself be an instance), it wouldn't check what you want it to check. :-)

Share:
14,754
Sam YC
Author by

Sam YC

Updated on June 15, 2022

Comments

  • Sam YC
    Sam YC almost 2 years

    I am just curious to ask this, maybe it is quite meaningless.

    When we are using instanceof in java, like:

    if (a instanceof Parent){ //"Parent" here is a parent class of "a"
    }
    

    why we can't use like below:

    if (a instanceof Parent.class){
    }
    

    Does the second 'instanceof' make more sense from the view of strict programming? What is the difference between "Parent" and "Parent.class"?