Reflection
Class Object
Learn how to obtain and use java.lang.Class instances.
Interview: Commonly tested on the three ways to obtain a Class instance and the difference between .class and getClass().
The class java.lang.Class is the entry point for reflection. An instance of this class represents the metadata of a loaded Java type.
Core Idea
A Class object holds the metadata representing a loaded type inside the JVM Metaspace.
Why It Matters
You must obtain the Class instance to perform any reflection operations like inspecting fields or invoking methods.
Interview Lens
Focuses on the difference between Class.forName() class loading and using class literals.
Three Ways to Obtain a Class Instance
- Class Literal:
MyClass.class. Resolved at compile-time. Safe and performant because it does not trigger dynamic loading. - Object Instance:
instance.getClass(). Dynamic lookup at runtime on a concrete object. - String Name:
Class.forName("com.pkg.MyClass"). Dynamically loads the class by name at runtime. ThrowsClassNotFoundExceptionif not found.
Code Walkthrough
This program demonstrates the three ways to get a Class object.
public class ClassObjectDemo { public static void main(String[] args) throws ClassNotFoundException { // Way 1: Class Literal Class c1 = String.class;// Way 2: Object Instance String str = "Hello"; Class c2 = str.getClass();
// Way 3: Class.forName() Class c3 = Class.forName("java.lang.String");
System.out.println("Are they equal? " + (c1 == c2 && c2 == c3)); // true (same metadata reference) } }
Interview-Relevant Information
Q: Does Class.forName() initialize static blocks?
Answer: Yes, by default Class.forName(String) loads and initializes the class, triggering static initialization blocks. If you only want to load the class metadata without running static initializers, use the overloaded signature: Class.forName(name, false, classLoader).
Quick Checklist
What are the three ways to get a Class object? Does Class.forName() initialize static blocks? If yes, you understand the Class object entry point.
Use Cases
Dynamic loading of JDBC database drivers at runtime.
Inspecting interface support inside plugin architectures.
Common Mistakes
Using Class.forName() with class names containing spelling errors, causing runtime ClassNotFoundExceptions.
Assuming primitive classes (like int.class) are equal to their wrapper classes (like Integer.class).