Is there something like instanceOf(Class<?> c) in Java?

后端 未结 7 1893
盖世英雄少女心
盖世英雄少女心 2020-11-27 17:15

I want to check if an object o is an instance of the class C or of a subclass of C.

For instance, if p is of clas

7条回答
  •  抹茶落季
    2020-11-27 18:00

    x instanceof Integer
    x instanceof Object
    

    you just have to use the right syntax

    for primitve types, you have to do it completely different. Since you cannot create methods for them , you need a class that keeps the method. So instead of "x.instanceOf(Integer.Class)", you have to call "MyClassComparer.instanceOf(x, Integer.Class)" or something like that. This could easily be implemented by overloading methods, but I fail to see a case when that functionality would be desireable at all.

提交回复
热议问题