Albert Albert - 4 months ago 29
Java Question

java: Class.isInstance vs Class.isAssignableFrom

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?

Answer

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.