Get class from an object in Java

Java 8Object Oriented ProgrammingProgramming

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());
raja
Published on 09-Jan-2019 14:56:48
Advertisements