Let clazz
be some Class
and obj
be some Object
.
Is
clazz.isAssignableFrom(obj.getClass())
always the same as
clazz.isInstance(obj)
?
If not, what are the differences?
The isAssignableFrom() method of java. lang. Class class is used to check if the specified class's object is compatible to be assigned to the instance of this Class. It will be compatible if both the classes are the same, or the specified class is a superclass or superinterface.
The instanceof operator and isInstance() method both are used for checking the class of the object. But the main difference comes when we want to check the class of objects dynamically then isInstance() method will work. There is no way we can do this by instanceof operator.
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.
isAssignableFrom() determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
clazz.isAssignableFrom(Foo.class)
will be true whenever the class represented by the clazz
object is a superclass or superinterface of Foo
.
clazz.isInstance(obj)
will be true whenever the object obj
is an instance of the class clazz
.
That is:
clazz.isAssignableFrom(obj.getClass()) == clazz.isInstance(obj)
is always true so long as clazz
and obj
are nonnull.
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