Three Ways to Obtain a Class Object
You'll learn the three standard methods for getting a Class object in Java's Reflection API.
Now that you understand what a Class object is, let's explore how to actually obtain one. Java provides three distinct approaches, each suited to different scenarios.
1. The .class Literal Syntax
The simplest way is using the .class literal directly on a type:
Class<String> stringClass = String.class;
Class<Integer> intClass = Integer.class;
Class<int> primitiveIntClass = int.class;
This works for any type—classes, interfaces, primitives, and arrays. It's compile-time safe and doesn't throw checked exceptions.
2. The getClass() Method
Every object inherits getClass() from Object, returning the runtime class of that instance:
String text = "Hello";
Class<?> textClass = text.getClass(); // returns String.class
Integer num = 42;
Class<?> numClass = num.getClass(); // returns Integer.class
This approach reveals the actual runtime type, which matters for polymorphic objects. Note: you can't use this on primitives (they aren't objects).
3. The Class.forName() Method
When you have the fully-qualified class name as a string at runtime:
try {
Class<?> loadedClass = Class.forName("java.lang.String");
} catch (ClassNotFoundException e) {
// Handle missing class
}
This dynamically loads the class if not already loaded. It's essential for reflection scenarios where class names come from configuration files or user input. It throws a checked exception if the class doesn't exist.
Choosing the Right Approach
Use .class when you know the type at compile time. Use getClass() when you need the runtime type of an instance. Use Class.forName() when working with class names determined dynamically.
Key Takeaway: Java offers three ways to obtain Class objects: .class literals (compile-time), getClass() (runtime instance), and Class.forName() (dynamic string-based loading)—each serving different reflection needs.