Java instanceof with class name

后端 未结 5 2152
抹茶落季
抹茶落季 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:17

    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.

提交回复
热议问题