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

后端 未结 7 1911
盖世英雄少女心
盖世英雄少女心 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 17:43

    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 class Point I want x.instanceOf(Point.class)

    Um... What? What are o, p and x?

    I want it to work also for primitive types. For instance, if x is an integer then x.instanceOf(Integer.class) and also x.instanceOf(Object.class) should be true.

    No. It shouldn't even compile. Primitives are not objects, and you cannot call methods on them.

    Anyway, there are three things, one of which can definitely achieve what you want (they differ somewhat in where exactly the apply:

    • The instanceof operator if you know the class at compile time.
    • Class.isInstance() if you want to check an object's class against a class not known at compile time.
    • Class.isAssignableFrom() if you want to check the assignability given two class objects.

提交回复
热议问题