12.1 Reflection Basics Explained
Reflection in Java SE 11 is a powerful feature that allows a program to examine and modify its own structure and behavior at runtime. Understanding the basics of reflection is essential for advanced Java programming, especially when dealing with dynamic and flexible applications.
Key Concepts
1. Class Objects
In Java, every object is an instance of a class. The Class
object represents the class of an object and provides methods to inspect the class at runtime. The Class
object can be obtained using the .class
syntax, the getClass()
method, or the Class.forName()
method.
Example
Class<?> clazz = MyClass.class; Class<?> clazz2 = obj.getClass(); Class<?> clazz3 = Class.forName("com.example.MyClass");
2. Inspecting Class Members
Reflection allows you to inspect the fields, methods, and constructors of a class. The Class
object provides methods like getFields()
, getMethods()
, and getConstructors()
to retrieve these members.
Example
Field[] fields = clazz.getFields(); Method[] methods = clazz.getMethods(); Constructor<?>[] constructors = clazz.getConstructors();
3. Accessing and Modifying Fields
Using reflection, you can access and modify the values of fields in an object, even if they are private. The Field
class provides methods like get()
and set()
to read and write field values.
Example
Field field = clazz.getDeclaredField("fieldName"); field.setAccessible(true); Object value = field.get(obj); field.set(obj, newValue);
4. Invoking Methods
Reflection allows you to invoke methods on an object dynamically. The Method
class provides the invoke()
method to call a method with specified arguments.
Example
Method method = clazz.getMethod("methodName", parameterTypes); Object result = method.invoke(obj, args);
5. Creating New Instances
Reflection enables the creation of new instances of a class using its constructors. The Constructor
class provides the newInstance()
method to create objects.
Example
Constructor<MyClass> constructor = MyClass.class.getConstructor(parameterTypes); MyClass obj = constructor.newInstance(args);
Examples and Analogies
Think of reflection as a powerful microscope that allows you to inspect and manipulate the inner workings of a Java object. For example, if you have a black box and you want to know what's inside without opening it, reflection lets you peek inside and even change its contents.
For instance, if you have a class with private fields and you want to access them from outside the class, reflection allows you to do so by bypassing the usual access controls. This is like having a secret key that unlocks hidden compartments in a locked box.
By mastering the basics of reflection, you can create more dynamic and flexible Java applications, enabling features like dependency injection, object serialization, and runtime class loading.