Reflection
Reflection allows code to inspect other code (classes, interfaces, fields, and methods) at runtime, without knowing the names of the interfaces, fields, methods at compile time.
The Class Object
Every type in Java including primitive types has an associated Class
object.
Class<?> c = Class.forName("java.util.ArrayList");
System.out.println(c.getName());
Inspecting Methods
Method[] methods = c.getMethods();
for (Method m : methods) {
System.out.println(m.getName());
}
Accessing Private Fields (The Hacker Way)
Reflection can break encapsulation by accessing private fields.
Field f = myObj.getClass().getDeclaredField("privateField");
f.setAccessible(true); // Unlock it!
System.out.println(f.get(myObj));
Full Example
Output
Click Run to execute your code
Summary
- Reflection is powerful but slow. Avoid it in performance-critical loops.
- It can break security and design principles (like private encapsulation).
- Extensively used by Frameworks (Spring, Hibernate, JUnit).
Enjoying these tutorials?