Core Concepts and Practical Implementation of Java Reflection Mechanism
Java reflection enables programs to inspect, acces, and modify structural information of classes, methods, fields, and constructors during runtime, rather than requiring all type information to be known at compile time. This capability enables highly flexible dynamic programming logic, and all supporting interfaces and classes are provided under the java.lang.reflect package.
Obtaining Class Objects
All reflection operations start with a Class object, which represents the type metadata of a target class. There are three standard ways to fetch this object:
- Access the static
.classattribute directly from the target type, e.g.Person.class - Call the
Class.forName(String fullyQualifiedClassName)static method, which is commonly used for dynamically loading classes by their full path - Invoke the
getClass()method on an existing instance of the target class, inherited fromjava.lang.Object
Fetching Class Metadata
The Class class exposes a set of utility methods to retrieve full metadata of the target type, including but not limited to:
- Class full name and simple name
- Belonging package information
- Inherited parent class
- All implemented interfaces
- Public and all declared constructors
- Public and all declared methods
- Public and all declared member fields
For example, calling getMethods() returns an array of all public methods defined in the class and inherited from parent classes, while getDeclaredMethods() returns all methods declared directly in the class regardless of access modifier.
Dynamic Object Instantiation
You can create instances of the target class dynamically via the Class object or its associated Constructor objects:
- Call
newInstance()directly on theClassobject (note this method is deprecated as of Java 9, as it only works with no-arg constructors and wraps checked exceptions improperly)
Class<?> personCls = Person.class;
Person defaultPerson = (Person) personCls.newInstance();
- Fetch a matching
Constructorinstance first, then call itsnewInstance()method to pass constructor parameters, which is the recommended approach for all Java versions:
Constructor<?> paramConstructor = personCls.getConstructor(String.class);
Object personInstance = paramConstructor.newInstance("Alice Miller");
Dynamic Method Invocation
The Method class provides the invoke() method to call the corresponding method on a target instance. You can fetch a Method object via getMethod() (for public methods) or getDeclaredMethod() (for any declared method):
Method greetMethod = personCls.getMethod("greet");
// Invoke the greet method on the personInstance object
greetMethod.invoke(personInstance);
For non-public methods, you need to call setAccessible(true) on the Method instance first to bypass access control checks.
Field Access and Modification
The Field class supports reading and writing the value of a corresponding field on a target instance:
Field fullNameField = personCls.getDeclaredField("fullName");
// Bypass access check for private field
fullNameField.setAccessible(true);
// Update the fullName value of personInstance to "Bob Carter"
fullNameField.set(personInstance, "Bob Carter");
// Read the current value of the field
String currentName = (String) fullNameField.get(personInstance);
Performance and Security Notes
Reflection operations introduce additional runtime type resolution overhead, so they typically execute slower than equivalent direct static calls. Additionally, the ability to bypass access control checks can break encapsulation and introduce security vulnerabilities if used improperly, so reflection should only be used when no static implementation alternative is available.
Complete Working Example
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Person {
private String fullName;
public Person(String fullName) {
this.fullName = fullName;
}
public void greet() {
System.out.printf("Greetings, my name is %s%n", fullName);
}
}
public class ReflectionTest {
public static void main(String[] args) throws Exception {
// Obtain Class object for Person type
Class<?> personCls = Person.class;
// Print class metadata
System.out.println("Target class full name: " + personCls.getName());
// Create instance via parameterized constructor
Constructor<?> constructor = personCls.getConstructor(String.class);
Object personInstance = constructor.newInstance("Alice Miller");
// Invoke public greet method
Method greetMethod = personCls.getMethod("greet");
greetMethod.invoke(personInstance);
// Modify private fullName field
Field nameField = personCls.getDeclaredField("fullName");
nameField.setAccessible(true);
nameField.set(personInstance, "Bob Carter");
// Verify field modification
greetMethod.invoke(personInstance);
}
}