Given a Class<?> superType
and a Object subInstance
, what are the differences between
superType.isInstance(subInstance)
and
superType.isAssignableFrom(subInstance.getClass())
(if any)?
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
In the scenario, there is no difference.
The difference between both methods are the parameters. One works with object and one with classes:
Class#isInstance(Object)
Determines if the specified Object is assignment-compatible with the object represented by this Class.
Class#isAssignableFrom(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()
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.
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