Reflection
Code that looks in the mirror.
Reflection
Analogy: concept
Reflection is like X-Ray Specs:
Normally, you can only see the outside of an object (Public methods). With Reflection, you can see the inside (Private fields), check what type it is, and even change its internal organs (Data) while it's alive!
X-Ray Specs
Inspect a "SecretBox" object to see its private fields, and then hack it!
Reflection (X-Ray Specs)
SecretBox
Private Access Only
Reflection Output
No data scanned yet.
*Reflection allows code to inspect and modify itself at runtime, even bypassing private access modifiers!
Key Concepts
- Introspection: The ability of a program to examine the type or properties of an object at runtime.
- Reflection: The ability to modify the structure and behavior of the program at runtime.
- Use Cases:
- IDEs (Auto-completion)
- Debuggers
- Testing Frameworks (JUnit uses reflection to find
@Testmethods) - Serialization Libraries (JSON parsers)
The Code
import java.lang.reflect.*;
class Secret {
private String password = "123";
}
Secret s = new Secret();
// s.password; // Error! Private access.
// Using Reflection
Field f = s.getClass().getDeclaredField("password");
f.setAccessible(true); // Bypass security!
System.out.println(f.get(s)); // Output: "123"
Up Next
Type System