Search code examples
javareflectioninstanceof

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


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

For instance, if x is of class Point I want x.instanceOf(Point.class) to be true and also x.instanceOf(Object.class) to be true.

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

Is there such a thing? If not, how can I implement such a method?


Solution

  • Class.isInstance does what you want.

    if (Point.class.isInstance(someObj)){
        ...
    }
    

    Of course, you shouldn't use it if you could use instanceof instead, but for reflection scenarios it often comes in handy.