Reflection in Java
Reflection is the ability for a running Java program to examine and manipulate its own classes, methods, and fields at runtime, even ones it has no compile-time reference to — given nothing but a String naming a class, reflection can inspect what fields and methods that class has, create an instance of it, and call its methods, all dynamically. Class.forName("com.example.MyClass") loads a class by name at runtime, and from the resulting Class object, methods like getDeclaredFields() and getDeclaredMethods() reveal everything about that class's structure that would normally only be visible by reading its source code directly.
Reflection is genuinely powerful but comes with real costs: it bypasses normal compile-time type checking, so mistakes surface as runtime exceptions instead, it's noticeably slower than direct method calls, and it can even reach past access modifiers to touch private fields and methods. That's exactly why frameworks needing genuine flexibility — dependency injection, serialization libraries, testing tools — rely on it heavily, while ordinary application code almost never needs to reach for it directly.
Loading a class by name
Class.forName("com.example.MyClass") loads a class dynamically at runtime, given just a String.
Inspecting structure
getDeclaredFields() and getDeclaredMethods() reveal a class's fields and methods without needing its source code.
Creating instances dynamically
Reflection can construct a new object of a class discovered only at runtime, with no compile-time reference to it.
Calling methods dynamically
A Method object obtained through reflection can be invoked on a target object, even without knowing that method at compile time.
Real costs
Reflection bypasses compile-time type checking, runs slower than direct calls, and can reach past access modifiers meant to restrict visibility.
public class ReflectionDemo { static class Sample { int value; String label; } public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("ReflectionDemo$Sample"); System.out.println("Class name: " + clazz.getSimpleName()); System.out.println("Field count: " + clazz.getDeclaredFields().length); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.