find out the class name of an object at runtime (java/example)

  • Given an instance of class in java.
  • We would like to find out the class name of an object.
  • We will use class Class to get name of class at runtime.
    • Class class has method getName, which returns the name of the entity (class, interface, array class, primitive type, or void).

1. Program: find out class name of object at run-time (java/example)

package org.learn;


import java.util.concurrent.atomic.AtomicInteger;

public class DemoGetClassName {

    public static void main(String[] args) {

        //print class name of Number
        printClassName(new Integer(100));

        //print class name of AtomicInteger
        printClassName(new AtomicInteger(200));

        //print class name of AtomicInteger
        printClassName(new Float(2710.00f));

        //print class name of String
        printClassName(new String ("DummyString"));
    }

    private static void printClassName(Object srcObject) {
        String name = srcObject.getClass().getName();
        System.out.printf("The class of %s is %s\n", srcObject, name);
    }
}

2. Program: find out class name of object at run-time (java/example)

The class of 100 is java.lang.Integer
The class of 200 is java.util.concurrent.atomic.AtomicInteger
The class of 2710.0 is java.lang.Float
The class of DummyString is java.lang.String
Scroll to Top