Is there an easy way to verify that an object belongs to a given class? For example, I could do
if(a.getClass() = (new MyClass()).getClass()) { //do something }
but this requires instantiating a new object on the fly each time, only to discard it. Is there a better way to check that "a" belongs to the class "MyClass"?
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does. Copied!
If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.
Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.
The instanceof
keyword, as described by the other answers, is usually what you would want. Keep in mind that instanceof
will return true
for superclasses as well.
If you want to see if an object is a direct instance of a class, you could compare the class. You can get the class object of an instance via getClass()
. And you can statically access a specific class via ClassName.class
.
So for example:
if (a.getClass() == X.class) { // do something }
In the above example, the condition is true if a
is an instance of X
, but not if a
is an instance of a subclass of X
.
In comparison:
if (a instanceof X) { // do something }
In the instanceof
example, the condition is true if a
is an instance of X
, or if a
is an instance of a subclass of X
.
Most of the time, instanceof
is right.
If you ever need to do this dynamically, you can use the following:
boolean isInstance(Object object, Class<?> type) { return type.isInstance(object); }
You can get an instance of java.lang.Class
by calling the instance method Object::getClass
on any object (returns the Class
which that object is an instance of), or you can use class literals (for example, String.class
, List.class
, int[].class
). There are other ways as well, through the reflection API (which Class
itself is the entry point for).
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