Get class from an object in Java


The runtime class of an object can be obtained using the java.lang.Object.getClass(). Also, the getName() method is used to get the name of the class.

A program that demonstrates getting the class of an object using the getClass() method is given as follows −

Example

 Live Demo

public class Demo {
   public static void main (String [] args) {
      Integer integer = new Integer(10);
      Class c = integer.getClass();
      System.out.println ("The class is: " + c.getName());
      c = new Demo().getClass();
      System.out.println ("The class is: " + c.getName());
   }
}

Output

The class is: java.lang.Integer
The class is: Demo

Now let us understand the above program.

First a new Integer is created. Then the getClass() method is used to obtain the runtime class. Finally the getName() method is used to get the name of the class i.e. java.lang.Integer and print it. A code snippet which demonstrates this is as follows −

Integer integer = new Integer(10);
Class c = integer.getClass();
System.out.println ("The class is: " + c.getName());

After this, the getClass() method is used to obtain the runtime class of an object of Demo. Then the getName() method is used to get the name of the class i.e. Demo and print it. A code snippet which demonstrates this is as follows −

c = new Demo().getClass();
System.out.println ("The class is: " + c.getName());

Updated on: 25-Jun-2020

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements