8

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

superType.isInstance(subInstance)

and

superType.isAssignableFrom(subInstance.getClass())

(if any)?

sp00m
  • 47,968
  • 31
  • 142
  • 252

4 Answers4

4

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.

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
3

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
AleX
  • 109
  • 4
  • 4
    The sample code seems to be proving nothing -- `cInt.isAssignableFrom(cInt)` is of course true, since it's testing itself. This is not a comparison to `cInt.isInstance(l)`, because `l` is a Long, not `Integer.TYPE`. – Nicole May 05 '15 at 02:02
1

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.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

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.

Svend Hansen
  • 3,277
  • 3
  • 31
  • 50