Java Reflection |
\\n \\nReflection API
\\nThe Java Reflection API provides a set of classes and interfaces for manipulating Class objects. The main classes include:
\\n- \\n
java.lang.ClassοΌRepresents the class's object. Provides methods to obtain the class's fields, methods, constructors, etc. \\n java.lang.reflect.Field- οΌRepresents the field (attribute) of a class. Provides the ability to access and modify the field.
java.lang.reflect.Constructor: represents the class's constructor. Provides the ability to create objects. \\n
java.lang.reflect.MethodοΌRepresents a method of a class. Provides the ability to invoke methods.capability.\\n Workflow
\\n- \\n
- Get `Class` object: First, obtain the `Class` object of the target class. \\n
- Get member information: Through the `Class` object, you can obtain the class's fields, methods, constructors, and other information. \\n
- Manipulate members: Through the Reflection API, you can read and modify field values, invoke methods, and create objects. \\n
1. Obtaining Class Objects
\\nEvery class in the JVM has an associated Class object. Class objects can be obtained in the following ways:
\\n- \\n
- Through class literals
Class<?> clazz = String.class;\\n String str = "Hello";\\nClass<?> clazz = str.getClass();\\n Class<?> clazz = Class.forName("java.lang.String"); \\n 2. Creating Objects
\\nYou can use reflection to dynamically create objects:
Class<?> clazz = Class.forName("java.lang.String");\\nObject obj = clazz.getDeclaredConstructor().newInstance(); 3. Accessing Fields
\\nFields of a class can be accessed and modified through reflection:
Class<?> clazz = Person.class;\\nField field = clazz.getDeclaredField("name");\\nfield.setAccessible(true); // If the field is private, it needs to be set accessible.\\nObject value = field.get(personInstance); // Get field value.\\nfield.set(personInstance, "New Name"); // Set field value.4. Calling Methods
\\nYou can call methods of a class using reflection:
Class<?> clazz = Person.class;\\nMethod method = clazz.getMethod("sayHello");\\nmethod.invoke(personInstance);\\nMethod methodWithArgs = clazz.getMethod("greet", String.class);\\nmethodWithArgs.invoke(personInstance, "World");5. Get Constructor
\\nYou can use reflection to obtain and invoke the constructor:
Class<?> clazz = Person.class;\\nConstructor<?> constructor = clazz.getConstructor(String.class, int.class);\\nObject obj = constructor.newInstance("John", 30);6. Obtaining Interfaces and Superclasses
\\nReflection can be used to obtain the interfaces implemented by a class and its superclass:
Class<?> clazz = Person.class;\\n// Get all interfaces.\\nClass<?>[] interfaces = clazz.getInterfaces();\\nfor (Class<?> i : interfaces) {\\n System.out.println("Interface: " + i.getName());\\n}\\n// Get the parent class.\\nClass<?> superClass = clazz.getSuperclass();\\nSystem.out.println("Superclass: " + superClass.getName()); Examples
import java.lang.reflect.Constructor;\\nimport java.lang.reflect.Field;\\nimport java.lang.reflect.Method;\\npublic class ReflectionExample {\\n public static void main(String[] args) throws Exception {\\n // Get Class object.\\n Class<?> clazz = Person.class;\\n // Create object.\\n Constructor<?> constructor = clazz.getConstructor(String.class, int.class);\\n Object person = constructor.newInstance("John", 30);\\n // Access the field.\\n Field nameField = clazz.getDeclaredField("name");\\n nameField.setAccessible(true);\\n System.out.println("Name: " + nameField.get(person));\\n // Modify the field.\\n nameField.set(person, "Doe");\\n System.out.println("Updated Name: " + nameField.get(person));\\n // Invoke method.\\n Method greetMethod = clazz.getMethod("greet", String.class);\\n greetMethod.invoke(person, "World");\\n }\\n}\\nclass Person {\\n private String name;\\n private int age;\\n public Person(String name, int age) {\\n this.name = name;\\n this.age = age;\\n }\\n public void greet(String message) {\\n System.out.println(name + " says: " + message);\\n }\\n}\\n Compile and execute the above code, the output result is:
\\nName: John\\nUpdated Name: Doe\\nDoe says: World
java.lang.reflect
\\n`java.lang.reflect` is the core package of Java's reflection mechanism, providing classes and interfaces for manipulating classes and their members (fields, methods, constructors, etc.). Through these APIs, developers can dynamically query and modify class structures at runtime.
\\n1. `Class` class
\\n- \\n
- Function: Represents a class object, providing methods to retrieve class information such as fields, methods, and constructors. \\n
- Main Methods:\\n
- \\n
getFields()οΌGet all public fields. \\n getDeclaredFields()οΌGet all declared fields, including private fields. \\n getMethods()οΌGet all public methods. \\n getDeclaredMethods()οΌGet all declared methods, including private methods. \\n getConstructors()οΌGet all public constructors. \\n getDeclaredConstructors(): Get all declared constructors, including private constructors. \\n getSuperclass()οΌGet the parent class of the class. \\n getInterfaces(): Retrieves all interfaces implemented by the class. \\n
\\n
2. `Field` Class
\\n- \\n
- Purpose: Represents a field (property) of a class, providing methods to access and modify the field's value. \\n
- Key Methods:\\n
- \\n
get(Object obj)οΌGet the field value of the specified object. \\n set(Object obj, Object value)οΌSet the field value of the specified object. \\n getType()οΌGet the data type of the field. \\n getModifiers(): Get the modifiers of the field (e.g., public, private). \\n
\\n
3. `Method` Class
\\n- \\n
- Purpose: Represents a method of a class, providing the capability to invoke methods. \\n
- Main Methods:\\n
- \\n
invoke(Object obj, Object... args)οΌInvoke the method of the specified object. \\n getReturnType()οΌGet the return type of the method. \\n getParameterTypes()οΌGet the parameter types of the method. \\n getModifiers()οΌGet the modifiers of the method (e.g., public, private). \\n
\\n
4. `Constructor` class
\\n- \\n
- Feature: Represents the class constructor, providing the ability to create objects. \\n
- Main methods:\\n
- \\n
newInstance(Object... initargs)οΌCreate a new instance using the specified constructor parameters. \\n getParameterTypes()οΌGet the parameter types of the constructor. \\n getModifiers()οΌGet the modifiers of the constructor (such as public, private). \\n
\\n
Example Code
\\nimport java.lang.reflect.Field;\\nimport java.lang.reflect.Method;\\nimport java.lang.reflect.Constructor;\\npublic class ReflectionExample {\\n public static void main(String[] args) throws Exception {\\n // Get Class object.\\n Class<?> clazz = Car.class;\\n // Create Car object.\\n Constructor<?> constructor = clazz.getConstructor(String.class, int.class);\\n Object car = constructor.newInstance("Toyota", 2020);\\n // Access and modify the field.\\n Field modelField = clazz.getDeclaredField("model");\\n Field yearField = clazz.getDeclaredField("year");\\n // Set the field as accessible (if the field is private).\\n modelField.setAccessible(true);\\n yearField.setAccessible(true);\\n // Print the original field value.\\n System.out.println("Original Model: " + modelField.get(car));\\n System.out.println("Original Year: " + yearField.get(car));\\n // Modify the field.Value\\n modelField.set(car, "Honda");\\n yearField.set(car, 2024);\\n // Print the modified field value.\\n System.out.println("Updated Model: " + modelField.get(car));\\n System.out.println("Updated Year: " + yearField.get(car));\\n // Invoke method.\\n Method startMethod = clazz.getMethod("start");\\n startMethod.invoke(car);\\n }\\n}\\nclass Car {\\n private String model;\\n private int year;\\n public Car(String model, int year) {\\n this.model = model;\\n this.year = year;\\n }\\n public void start() {\\n System.out.println("The " + model + " car of year " + year + " is starting.");\\n }\\n}\\n Compile and execute the above code, the output result is:
\\nOriginal Model: Toyota\\nOriginal Year: 2020\\nUpdated Model: Honda\\nUpdated Year: 2024\\nThe Honda car of year 2024 is starting.\\n
YouTip