Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Spring Framework ReflectionUtils: Simplifying Java Reflection Operations

Tech Apr 17 8

ReflectionUtils is a utility class in the org.springframework.util package designed too streamline common Java reflection tasks. It abstracts boilerplate code to operations such as field and method tarversal, access, and invocation.

Key capabilities include:

  • Traversing members: Methods like doWithFields() and doWithMethods() iterate over a class's dcelared fields or methods, applying a callback action.
  • Finding members: Functions like findField() and findMethod() locate specific fields or methods by name and type.
  • Accessing fields: Utilities such as getField() and setField() read or modify field values, handling accessibility checks.
  • Invoking methods: The invokeMethod() functon calls methods dynamically with specified arguments.
  • Copying state: shallowCopyFieldState() copies field values between objects.

Code Examples

Iterating Over Fields

import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;

public class FieldInspector {
    private String firstName;
    private String lastName;
    private int birthYear;

    public static void main(String[] args) {
        ReflectionUtils.doWithFields(FieldInspector.class, field -> {
            System.out.println("Field: " + field.getName() + ", Type: " + field.getType().getSimpleName());
        });
    }
}

Reading Field Values

import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;

public class ValueReader {
    private String username;
    private String email;
    private int level;

    public static void main(String[] args) {
        ValueReader instance = new ValueReader();
        instance.username = "admin";
        instance.email = "admin@example.com";
        instance.level = 5;

        ReflectionUtils.doWithFields(ValueReader.class, field -> {
            ReflectionUtils.makeAccessible(field);
            Object value = ReflectionUtils.getField(field, instance);
            System.out.println(field.getName() + " = " + value);
        });
    }
}

Modifying Field Values

import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;

public class ValueUpdater {
    private String status;
    private int count;

    public static void main(String[] args) {
        ValueUpdater obj = new ValueUpdater();
        obj.status = "initial";
        obj.count = 10;

        Field statusField = ReflectionUtils.findField(ValueUpdater.class, "status");
        if (statusField != null) {
            ReflectionUtils.makeAccessible(statusField);
            ReflectionUtils.setField(statusField, obj, "updated");
        }

        System.out.println("Status: " + obj.status + ", Count: " + obj.count);
    }
}

Invoking Methods

import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Method;

public class MethodInvoker {
    public void greet() {
        System.out.println("Hello from greet method");
    }

    public String echo(String message) {
        return "Echo: " + message;
    }

    public static void main(String[] args) {
        MethodInvoker service = new MethodInvoker();

        Method greetMethod = ReflectionUtils.findMethod(MethodInvoker.class, "greet");
        if (greetMethod != null) {
            ReflectionUtils.invokeMethod(greetMethod, service);
        }

        Method echoMethod = ReflectionUtils.findMethod(MethodInvoker.class, "echo", String.class);
        if (echoMethod != null) {
            String result = (String) ReflectionUtils.invokeMethod(echoMethod, service, "Test Message");
            System.out.println(result);
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.