O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting a Class Descriptor

Problem

You want to get a Class object from a class name or instance.

Solution

If the class name is known at compile time, you can get the class instance using the compiler keyword .class , which works on any object. However, the Object class does not have class as a field, so this strikes some observers as a bit of a hack. Nonetheless, it works. Use it.

Otherwise, if you have an object (an instance of a class), you can call the java.lang.Object method getClass( ) , which returns the Class object for the object’s class (now that was a mouthful!):

import java.util.*;
/**
 * Show the Class keyword and getClass(  ) method in action.
 */
public class ClassKeyword {
    public static void main(String[] argv) {
        System.out.println("Trying the ClassName.class keyword:");
        System.out.println("Object class: " + Object.class);
        System.out.println("String class: " + String.class);
        System.out.println("Calendar class: " + Calendar.class);
        System.out.println("Current class: " + ClassKeyword.class);
        System.out.println(  );

        System.out.println("Trying the instance.getClass(  ) method:");
        System.out.println("Robin the Fearless".getClass(  ));
        System.out.println(Calendar.getInstance().getClass(  ));
    }
}

When we run it, we see:

C:\javasrc\reflect>java ClassKeyword Trying the ClassName.class keyword: Object class: class java.lang.Object String class: class java.lang.String Calendar class: class java.util.Calendar Current class: class ClassKeyword Trying the instance.getClass( ) method: class ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required