Obtaining Class Objects: .class and getClass()
You'll learn the two primary ways to get a Class object that represents a type at runtime.
The Core Idea
In the previous lesson, you learned that every type in Java has a Class object representing it at runtime. But how do you actually get that Class object? Java provides two main approaches: the class literal (.class) and the getClass() method.
Using the Class Literal: .class
The class literal is the simplest way. Just append .class to any type name:
Class<String> stringClass = String.class;
Class<Integer> intClass = Integer.class;
You can use this even when you don't have an instance of the class. It works with any type—classes you've written, built-in classes, even primitive types.
Class<int> primitiveIntClass = int.class;
Using the getClass() Method
Every object inherits the getClass() method. Call it on any object instance to get its runtime Class:
String text = "Hello";
Class<?> textClass = text.getClass(); // returns String.class
Key difference: You need an actual object to call getClass(), whereas .class works without any instance.
When to Use Each
- Use
.classwhen you know the type at compile time and want to reference the class itself - Use
getClass()when you have an object and want to discover its actual runtime type
Key Takeaway: Use .class to obtain a Class object directly from a type name, or call getClass() on any object instance to get its runtime class—both give you access to the same Class object for that type.