YouTip LogoYouTip

Java Reflection

Java Reflection | \\n\\n

Java Reflection |

\\n \\n
\\n
\\n

Reflection API

\\n

The 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.Method:Represents a method of a class. Provides the ability to invoke methods.capability.\\n
  • java.lang.reflect.Constructor: represents the class's constructor. Provides the ability to create objects.
  • \\n
\\n
\\n
\\n

Workflow

\\n
    \\n
  1. Get `Class` object: First, obtain the `Class` object of the target class.
  2. \\n
  3. Get member information: Through the `Class` object, you can obtain the class's fields, methods, constructors, and other information.
  4. \\n
  5. Manipulate members: Through the Reflection API, you can read and modify field values, invoke methods, and create objects.
  6. \\n
\\n
\\n
\\n

1. Obtaining Class Objects

\\n

Every 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
  • Through object instance:
  • \\n
    String str = "Hello";\\nClass<?> clazz = str.getClass();
    \\n
  • Through Class..forName() Method:
  • \\n
    Class<?> clazz = Class.forName("java.lang.String");
\\n
\\n
\\n

2. Creating Objects

\\n

You can use reflection to dynamically create objects:

Class<?> clazz = Class.forName("java.lang.String");\\nObject obj = clazz.getDeclaredConstructor().newInstance();
\\n
\\n

3. Accessing Fields

\\n

Fields 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.
\\n
\\n

4. Calling Methods

\\n

You 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");
\\n
\\n

5. Get Constructor

\\n

You 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);
\\n
\\n

6. Obtaining Interfaces and Superclasses

\\n

Reflection 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());
\\n
\\n

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:

\\n
Name: John\\nUpdated Name: Doe\\nDoe says: World
\\n
\\n

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.

\\n Image 1\\n

1. `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
  • \\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
  • \\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
  • \\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
  • \\n
\\n

Example Code

\\n
import 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:

\\n
Original Model: Toyota\\nOriginal Year: 2020\\nUpdated Model: Honda\\nUpdated Year: 2024\\nThe Honda car of year 2024 is starting.
\\n
\\n
← Flask TutorialZig Error β†’