Java Class isInstance() Method



Description

The Java Class isInstance() method determines if the specified Object is assignment-compatible with the object represented by this Class. It is dynamic equivalent of the Java language instanceof operator.

Declaration

Following is the declaration for java.lang.Class.isInstance() method

public boolean isInstance(Object obj)

Parameters

obj − This is the object to check.

Return Value

This method returns true if obj is an instance of this class.

Exception

NA

Getting Instance Status of an Assignment Compatible Class Example

The following example shows the usage of java.lang.Class.Instance() method. In this program, we've retrieved Class of Long and created instances of Long. Using Instance(), we've retrieved instance status of Long and result is printed.

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // Long object represented by class object
      Class cls = Long.class;

      Long l = Long.valueOf(86576);

      // checking for Long instance
      boolean retval = cls.isInstance(l);
      System.out.println(l + " is Long ? " + retval);      
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

86576 is Long ? true

Getting Instance Status of an Assignment Incompatible Class Example

The following example shows the usage of java.lang.Class.Instance() method. In this program, we've retrieved Class of Long and created instance of Double. Using Instance(), we've retrieved instance status and result is printed.

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // Long object represented by class object
      Class cls = Long.class;

      Double d = Double.valueOf(3.5);

      // checking for Long instance
      boolean retval = cls.isInstance(d);
      System.out.println(d + " is Long ? " + retval);        
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

3.5 is Long ? false
java_lang_class.htm
Advertisements