Given a Class<?> superType
and a Object subInstance
, what are the differences between
superType.isInstance(subInstance)
and
superType.isAssignableFrom(subInstance.getClass())
(if any)?
Given a Class<?> superType
and a Object subInstance
, what are the differences between
superType.isInstance(subInstance)
and
superType.isAssignableFrom(subInstance.getClass())
(if any)?
In the scenario, there is no difference.
The difference between both methods are the parameters. One works with object and one with classes:
Determines if the specified Object is assignment-compatible with the object represented by this Class.
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.
isAssignableFrom
also tests whether the type can be converted via an identity conversion or via a widening reference conversion.
Class<?> cInt = Integer.TYPE;
Long l = new Long(123);
System.out.println(cInt.isInstance(l)); // false
System.out.println(cInt.isAssignableFrom(cInt)); // true
isAssignableFrom()
will be true whenever the class represented by the class object is a superclass or superinterface of subInstance.getClass()
isInstance()
will be true whenever the object subInstance
is an instance of superType
.
So the basic difference is that isInstance
works with instances isAssignableFrom
works with classes.
I often use isAssignableFrom
if I don't have an instance/don't want to instantiate the class for some reason. Otherwise you can use both.
From the Java API:
isInstance(Object obj)
Determines if the specified Object is assignment-compatible with the object represented by this Class.
isAssignableFrom(Class<?> cls)
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.
So it sounds like the two methods do very similar things, but one takes an Object
and looks at the Class
of that object, while the other one takes a Class
.