Sunday, 27 May 2018

isInstance(): Check object compatibility of a class

'isInstance()' method is used to check whether the specified object is assignment-compatible with the object represented by this Class. It is the dynamic equivalent of 'instanceof' operator.

By using 'isInstance()', instanceof operator, you can check whether the object can be casted to other type or not.

For example, let’s see the definition of Integer class, it looks like below.



public final class Integer extends Number implements Comparable<Integer> {

}

As you see, Integer is a subclass of Number, Comparable, and Object (Object is the super class for all the classes). Now if you define, an integer variable, you can assign it to Number, Comparable and Object types. You can check this compatibility using 'isInstance' method.

Test.java

package com.sample.test;

public class Test {

 public static void main(String args[]) {

  Integer var1 = new Integer(10);

  System.out.println("Can I assign var1 to Integer : " + Integer.class.isInstance(var1));
  System.out.println("Can I assign var1 to Number : " + Number.class.isInstance(var1));
  System.out.println("Can I assign var1 to Comparable : " + Comparable.class.isInstance(var1));
  System.out.println("Can I assign var1 to Object : " + Object.class.isInstance(var1));

  System.out.println("Can I assign var1 to Double : " + Double.class.isInstance(var1));
  System.out.println("Can I assign var1 to Float : " + Float.class.isInstance(var1));
 }
}

Output

Can I assign var1 to Integer : true
Can I assign var1 to Number : true
Can I assign var1 to Comparable : true
Can I assign var1 to Object : true
Can I assign var1 to Double : false
Can I assign var1 to Float : false


Previous                                                 Next                                                 Home

No comments:

Post a Comment