Course contentsShow
← Java
Lesson 2330 of 2,87045. Reflection APIFree lesson

The Class Object: Getting Class Metadata

Learn how to obtain Class objects using .class, .getClass(), and Class.forName() to access type information.

The Class Object: Getting Class Metadata

You'll learn how to retrieve Class objects using three different techniques to access runtime type information.

Understanding Class Metadata Access

In Java's Reflection API, the Class object is your gateway to inspecting types at runtime. Think of it as looking up a blueprint in a library—you need to find the right blueprint before you can study its details. Java gives you three distinct ways to obtain this blueprint:

The Three Retrieval Methods

1. The .class literal — Use this when you know the type at compile time:

Class<String> stringClass = String.class;
Class<Integer> intClass = Integer.class;

2. The getClass() method — Call this on any object instance to discover its actual runtime type:

String text = "Hello";
Class<?> cls = text.getClass(); // Returns String.class

3. The Class.forName() method — Use this for dynamic loading when the type name comes from external sources (configuration files, user input):

Class<?> cls = Class.forName("java.lang.String");

When to Use Each Approach

  • .class is fastest and type-safe—prefer it when the type is known at compile time
  • getClass() reveals the actual runtime type of an object, useful when dealing with polymorphism
  • Class.forName() enables dynamic type discovery but requires handling ClassNotFoundException

Once you have a Class object, you've unlocked the door to reflection: you can inspect methods, fields, constructors, annotations, and more.

Key Takeaway: Java provides three ways to obtain Class objects—.class for compile-time types, .getClass() for runtime object types, and Class.forName() for dynamic string-based loading—each serving as your entry point to reflection metadata.