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)
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?
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.
For instanceof you need to know the exact class at compile time. For isInstance the class is decided at run time.
Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With