The java.lang.Object.getClass()
method returns the runtime class of an object.
The operator instanceof
is used when you know the kind of class you want to check against in advance.
The function isInstance()
is primarily intended for use in code dealing with runtime identification.
For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:
public boolean areObjectsAssignable(Object left, Object right) { return left.getClass().isInstance(right); }
The example code below produces the following when run from the command window:
C:\work>java ObjectDemo Thu Mar 22 16:16:39 EDT 2018 cal.getClass(): class java.util.GregorianCalendar cal instanceof GregorianCalendar: true c: class java.lang.String Class of Object obj is : java.lang.String i.getClass(): class java.lang.Integer r.getClass(): class Gen r.getClass().getName(): Gen r.getClass().isInstance(i): false r instanceof Gen: true obj instanceof Gen: true
ObjectDemo.java
import java.util.GregorianCalendar; public class ObjectDemo { public static void main(String[] args) { // create a new ObjectDemo object GregorianCalendar cal = new GregorianCalendar(); // print current time System.out.println("" + cal.getTime()); // print the class of cal System.out.println("cal.getClass(): " + cal.getClass()); System.out.println("cal instanceof GregorianCalendar: " + (cal instanceof GregorianCalendar)); System.out.println(); Object obj = new String("Java programming"); Class c = obj.getClass(); System.out.println("c: " + c); System.out.println("Class of Object obj is : " + c.getName()); System.out.println(); // create a new Integer Integer i = new Integer(5); // print the class of i System.out.println("i.getClass(): " + i.getClass()); System.out.println(); Gen r = new Gen("G1"); System.out.println("r.getClass(): " + r.getClass()); System.out.println("r.getClass().getName(): " + r.getClass().getName()); System.out.println(); obj = Object.class.cast(r); System.out.println("r.getClass().isInstance(i): " + r.getClass().isInstance(i)); System.out.println("r instanceof Gen: " + (r instanceof Gen)); System.out.println("obj instanceof Gen: " + (obj instanceof Gen)); } } class Gen { String name; Gen(String str) { name = str; } public String toString() { return name; } }
Maintained by John Loomis, updated Thu Mar 22 16:15:58 2018