Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class#isInstance vs Class#isAssignableFrom [duplicate]

Given a Class<?> superType and a Object subInstance, what are the differences between

superType.isInstance(subInstance)

and

superType.isAssignableFrom(subInstance.getClass())

(if any)?

like image 660
sp00m Avatar asked Oct 29 '13 16:10

sp00m


3 Answers

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
like image 95
AleX Avatar answered Sep 24 '22 05:09

AleX


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.

like image 21
Philipp Sander Avatar answered Sep 22 '22 05:09

Philipp Sander


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.

like image 22
Adam Arold Avatar answered Sep 23 '22 05:09

Adam Arold