java

How to determine the class name of an object in Java

Determining the type of an object in Java means figuring out what kind of object it is. In this tutorial, we are going to see how to determine the class name of an object in Java.

  • instanceof
  • getClass()
  • isInstance()

 

Determine the class name of an object using the instanceof keyword:

The “instanceof” keyword is used to test whether the object is an instance of the specified type (class or subclass or interface).

public class MyClass {
	public static void main(String args[]){
		MyClass obj = new MyClass();
		System.out.println(obj instanceof MyClass);
	}
}

Output:

true

 
[st_adsense]  

Determine the class name of an object using the getClass() method:

The getClass() method is a method of the Object class. This method returns the class of this object.

public class Main {
    public static void main(String[] args) 
    { 
        Object obj = new String("StackHowTo"); 
        Class c = obj.getClass(); 
        System.out.println("The class of the object obj is : " + c.getName()); 
    } 
}

Output:

The class of the object obj is : java.lang.String
[st_adsense]  

Determine the class name of an object using the isInstance() method:

The isInstance() method of the java.lang.Class class is used to check whether the specified object is compatible to be assigned to the instance of this class. The method returns true if the specified object is not null and can be converted to the instance of this class. Otherwise it returns false.

import java.lang.*;

public class Main {
   public static void main(String[] args) {
      Class c = Long.class;
      Long l = new Long(120005);
      boolean b = c.isInstance(l);
      System.out.println(l + " is of type Long ? " + b);
   }
}

Output:

120005 is of type Long ? true
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

Leave a Reply

Your email address will not be published. Required fields are marked *