Java.lang.Class.isInstance() Method



Description

The java.lang.Class.isInstance() 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

Example

The following example shows the usage of java.lang.Class.isInstance() method.

package com.tutorialspoint;

import java.lang.*;

public class ClassDemo {

   public static void main(String[] args) {

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

      Long l = new Long(86576);
      Double d = new Double(3.5);

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

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

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

86576 is Long ? true
3.5 is Long ? false
java_lang_class.htm
Advertisements