SoFunction
Updated on 2025-03-04

Analysis of the implementation principle of java reflection mechanism and beanUtils

1. Description of the reflection mechanism

Java's reflection mechanism allows programs to check and operate classes, methods, fields and other structures at runtime. Through reflection, objects can be created, methods can be called, and values ​​of fields can be obtained/set without determining these operations at compile time.

The core class of reflection isIn the packageMethodFieldandConstructorwait. Use reflections to pay attention to performance overhead and security issues.

  • Get the Class object of the class
Class<?> clazz = ;
  • Instantiate an object
MyClass myObject = (MyClass) ().newInstance();
  • Get and call methods
Method method = ("methodName", parameterTypes);
(true); // If the method is private, you need to set accessible to trueObject result = (myObject, args);
  • Get and set field values
Field field = ("fieldName");
(true); // If the field is private, you need to set accessible to trueObject value = (myObject);
(myObject, newValue);
  • Operation constructor
Constructor&lt;?&gt; constructor = (parameterTypes);
(true); // If the constructor is private, you need to set accessible to trueMyClass myObject = (MyClass) (args);

,DTO,PO instructions

VO (Value Object) value object

VO is the data used for display. No matter whether the display method is a web page, a client, or an APP, as long as this thing is visible to people, this is called VO. Everyone understands this. Anyway, the objects returned by our interface to the front end are all returned with VO. Unlike DTO, VO is returned to the front end, and DTO is used when we receive it from the front end, that is, one is to enter the parameter and the other is to return the result.

DTO (Data Transfer Object) Data Transfer Object

This transmission usually refers to the transmission between the front and back ends

DTO is a relatively special object, and it has two forms of existence:

  • One is the object used for the interaction between the front-end and the back-end
  • The other is a transmission object between microservices, which we usually use DTO to transmit.

PO (Persistant Object) Persistant Object

PO is easier to understand. Simply put, PO is a record in the database. The data structure of a PO corresponds to the structure of the table in the library. A record in the table is a PO object. Usually there is no other method in PO except get and set. For PO, the quantity is relatively fixed and will not exceed the number of database tables, which is equivalent to BO. These two concepts are consistent.

The implementation principle

When data transmission is carried out in various layers of the backend, beanUtils is often used to copy beans, and the implementation principle is to implement it through Java's radiation mechanism.

package ;

    private static void copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String... ignoreProperties) throws BeansException {
        (source, "Source must not be null");
        (target, "Target must not be null");
        Class<?> actualEditable = ();
        if (editable != null) {
            if (!(target)) {
                throw new IllegalArgumentException("Target class [" + ().getName() + "] not assignable to Editable class [" + () + "]");
            }

            actualEditable = editable;
        }

        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = ignoreProperties != null ? (ignoreProperties) : null;
        PropertyDescriptor[] var7 = targetPds;
        int var8 = ;

        for(int var9 = 0; var9 < var8; ++var9) {
            PropertyDescriptor targetPd = var7[var9];
            Method writeMethod = ();
            if (writeMethod != null && (ignoreList == null || !(()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor((), ());
                if (sourcePd != null) {
                    Method readMethod = ();
                    if (readMethod != null) {
                        ResolvableType sourceResolvableType = (readMethod);
                        ResolvableType targetResolvableType = (writeMethod, 0);
                        boolean isAssignable = !() && !() ? (sourceResolvableType) : (()[0], ());
                        if (isAssignable) {
                            try {
                                if (!(().getModifiers())) {
                                    (true);
                                }

                                Object value = (source);
                                if (!(().getModifiers())) {
                                    (true);
                                }

                                (target, value);
                            } catch (Throwable var18) {
                                throw new FatalBeanException("Could not copy property '" + () + "' from source to target", var18);
                            }
                        }
                    }
                }
            }
        }

    }

Simple examples

public class BeanToolUtils {

    public static void copy(Object source, Object target) throws Exception {
        Class&lt;?&gt; sourceClass = ();
        Class&lt;?&gt; targeteClass = ();
        Field[] fields = ();
        // Output field information        for (Field field : fields) {
            String name = ();
            if ("serialVersionUID".equals(name)) {
                continue;
            }
            String getterName = "get" + (0, 1).toUpperCase() + (1);
            String setterName = "set" + (0, 1).toUpperCase() + (1);

            Method getMethod = (getterName);
            if(!(getMethod)){
                Object val = (source);

                Method setMethod = (setterName,());
                (target, val);
            }

        }
    }
}

illustrate:

Get the class object of the target bean, obtain all attributes of the target bean through the class object, loop attribute information, get the attribute get and set methods, execute the get method of the source bean to obtain the attribute value, execute the set method of the target bean, set the attribute value, and complete the bean assignment operation.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.