Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata