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