HOWTO · Java

Get an Object's Runtime Class in Java

Learn how Java's getClass() method returns an object's runtime class, and how to use it with wrapper objects.

On this page

Java has no typeof operator. To inspect an object’s runtime class, call getClass() on a non-null object reference. Primitive values such as int and char are not objects and cannot call this method directly; box a primitive first to use this approach. Java also offers other ways to work with type information, so getClass() is useful when you need the actual class of an existing object.
Questions about types and operators are grouped together in the Java Tutorial, including how Java answers the typeof question.

Get an Object’s Runtime Class in Java

getClass() is defined by Object and returns a Class object describing the receiver’s runtime class. For example, a String reference can call it directly. Printing that Class object includes the package name, as class java.lang.String.

This complete Java program prints a string and the class of the object it references:

class RuntimeClassExample {
    public static void main(String[] args) {
        String message = "Hello";
        System.out.println(message);
        System.out.println("Class: " + message.getClass());
    }
}

Its stdout is:

Hello
Class: class java.lang.String

If you start with a primitive, assign it to a wrapper object such as Integer or Character before calling getClass(). Boxing converts a primitive value to its corresponding wrapper object. The reference must point to an object when you call the method; a null reference has no receiver.

Get the Runtime Class of Wrapper Objects in Java

Wrapper classes let you inspect objects that represent primitive values. This example uses Integer and Character. getClass() identifies each object’s runtime class, while getSimpleName() returns its name without the package qualification.

class WrapperClassExample {
    public static void main(String[] args) {
        Integer count = 20;
        Character letter = 'G';

        System.out.println("Integer class: " + count.getClass());
        System.out.println("Character class: " + letter.getClass());
        System.out.println("Integer simple name: " + count.getClass().getSimpleName());
        System.out.println("Character simple name: " + letter.getClass().getSimpleName());
    }
}

The class names shown by these calls are java.lang.Integer and java.lang.Character; their simple names are Integer and Character.