not Java instanceof with class name



java instanceof generic (4)

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"?


Answer #1

Parent is the name of a type. Parent.class is essentially a static variable that refers to an object (specifically, an instance of Class). You want to ask whether a is an instance of the Parent type, not whether it's an instance of an object that is itself an instance of some other type (named Class).


Answer #2

The static Parent.class member is actually an object. You could assign it to a variable of type Object or type Class if you wanted to:

Object o = Parent.class;
Class c = Parent.class;

Parent on the other hand isn't an object or a variable: it is a Type Name, as per the Java spec.

If you could do this...

a instanceof Parent.class

Since Parent.class is an object then you could feasibly could also do this:

Cat myCat = new DomesticLonghair();
a instanceof myCat;

... which is just silly.


Answer #3

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?


Answer #4

When you write Parent.class then that means you are creating a java.lang.Class object for your Parent class. So if (a instanceof Parent.class){ } this will not work for you.

For more details on Class class take a look of following links :
Class

Instances of the class Class represent classes and interfaces in a running Java application. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.





instanceof