Java instanceof with class name

后端 未结 5 1816
抹茶落季
抹茶落季 2021-02-20 00:45

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          


        
5条回答
  •  有刺的猬
    2021-02-20 01:13

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

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

    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?

提交回复
热议问题