![]() |
VOOZH | about |
Reflection in Java allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even when their details are unknown at compile time. It is provided through the java.lang.reflect package and is widely used in frameworks and libraries.
Java provides reflection through the following key classes:
These classes are located in the java.lang and java.lang.reflect packages.
Before performing any reflection operation, a Class object must be obtained. The Class object represents the runtime metadata of a class, such as its methods, fields, and constructors.
Ways to Get Class Object
Reflection allows objects to be created dynamically at runtime without using the new keyword. This is done by retrieving a Constructor object and invoking it programmatically.
Object Created
Explanation:
Using reflection, methods of a class can be discovered and invoked at runtime by their names. This is useful when method details are not known at compile time.
Method Invoked
Explanation:
Reflection provides the ability to access and modify class fields dynamically, including private fields. This is achieved using the Field class and can bypass access restrictions if required.
Hello
Explanation:
Feature | Reflection | Normal Code |
|---|---|---|
Compile-time Safety | No | Yes |
Performance | Slower | Faster |
Performance | High | Low |
Security | Lower | Higher |
Note:
- Reflection is powerful but expensive
- Avoid using it in performance-critical code
- Prefer normal object access when possible
- Use reflection mainly in frameworks