Download the JDK
Search the Tutorials
Hide the TOC
Trail: The Reflection API
Lesson: Examining Classes
Examining Classes
Retrieving Class Objects
Getting the Class Name
Discovering Class Modifiers
Finding Superclasses
Identifying the Interfaces Implemented by a Class
Examining Interfaces
Identifying Class Fields
Discovering Class Constructors
Obtaining Method Information
Home Page > The Reflection API > Examining Classes
« Previous • Trail • Next »
Retrieving Class Objects

> You can retrieve a `Class` object in several ways:
> - If an instance of the class is available, you can invoke `Object.getClass`. The `getClass` method is useful when you want to examine an object but you don't know its class. The following line of code gets the `Class` object for an object named `mystery`:

>   >     Class c = mystery.getClass();

> - If you want to retrieve the `Class` object for the superclass that another `Class` object reflects, invoke the `getSuperclass` method. In the following example, `getSuperclass` returns the `Class` object associated with the `TextComponent` class, because `TextComponent` is the superclass of `TextField`:

>   >     TextField t = new TextField();
>   >     Class c = t.getClass();
>   >     Class s = c.getSuperclass();

> - If you know the name of the class at compile time, you can retrieve its `Class` object by appending `.class` to its name. In the next example, the `Class` object that represents the `Button` class is retrieved:

>   >     Class c = java.awt.Button.class;

> - If the class name is unknown at compile time, but available at runtime, you can use the `forName` method. In the following example, if the `String` named `strg` is set to "java.awt.Button" then `forName` returns the `Class` object associated with the `Button` class:

>   >     Class c = Class.forName(strg);

« Previous • Trail • Next »
Previous page: Examining Classes
Next page: Getting the Class Name