Home  >  Article  >  Java  >  How to assign values ​​to object properties using Java reflection?

How to assign values ​​to object properties using Java reflection?

WBOY
WBOYforward
2023-05-07 10:43:191878browse

Preface

I recently encountered a problem in a project, which is to implement a universal method for converting multiple languages ​​in the future. Based on this requirement, I decided to use reflection to implement it, and set the object properties based on reflection. Attribute value, the following is a method to use reflection to set the object attribute value

Method 1: Here the Field attribute of the set side of Field is used, then the visibility is set, then a value is set, and finally printing

//Assign a value to a variable and assign a value to a field of the object object

f.set(object, value);

//After you get an instance of the Field class, you can Call one of the methods

//Method: get(Object obj) Returns the value of the field represented by this Field on the specified object obj

package com.example.reflectiondemo;
 
import java.lang.reflect.Field;
 
/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2023/01/04 19:52
 */
public class ReflectMain {
 
    private String readOnly;
 
    public String getReadOnly() {
        return readOnly;
    }
 
    public void setReadOnly(String readOnly) {
        System.out.println("set");
        this.readOnly = readOnly;
    }
 
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        ReflectMain t = new ReflectMain();
        Field f = t.getClass().getDeclaredField("readOnly");
        f.setAccessible(true);
        f.set(t, "test");
        System.out.println(t.getReadOnly());
 
    }
}

Method 2: Use the invoke method

package com.example.reflectiondemo;
 
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
/**
 * @program my-project-model
 * @description:
 * @author: lee
 * @create: 2023/01/04 19:52
 */
public class ReflectMain {
 
    private String readOnly;
 
    public String getReadOnly() {
        return readOnly;
    }
 
    public void setReadOnly(String readOnly) {
        System.out.println("set");
        this.readOnly = readOnly;
    }
 
    //    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//        ReflectMain t = new ReflectMain();
//        Field f = t.getClass().getDeclaredField("readOnly");
//        f.setAccessible(true);
//        f.set(t, "test");
//        System.out.println(t.getReadOnly());
//
//    }
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ReflectMain t = new ReflectMain();
        Method setReadOnly = t.getClass().getMethod("setReadOnly", String.class);
        String s = "test2";
        setReadOnly.invoke(t, s);
        System.out.println(t.getReadOnly());
 
    }
}

How to assign values ​​to object properties using Java reflection?

It can be seen that using reflection we can easily set each attribute. Even for private attributes, we can easily set the attribute value. Let’s use this demo example below. This sets up our initial functionality.

Summary:

In other words, the first method completes the assignment without calling the set method of the attribute.

But the second method is by calling the attribute set method to complete the assignment.

So, if you want to change the value of the program's attributes in the program and also want to do some additional things, you can write these things into the set method and use the second method

public class MultiLangContentUtil {
 
    /**
     * 从PO查询数据赋值到DTO
     * 注意!!这里的多语字段根据
     * 简体中文的变量名 英文名和繁体名需要根据规则进行 指定
     * 规则如下
     * 英文名=简体中文名2
     * 繁体名=简体中文名3
     *
     * @param targetPO        数据库中查询出的数据
     * @param targetDTO       将要转换的对象DTO
     * @param targetMultiName 需要展示的多语字段
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void setMultiLangDTOName(Object targetPO, Object targetDTO, String targetMultiName) {
        try {
 
            String locale = MultiLangContentUtil.getLocale();
            Class<?> targetDTOClass = targetDTO.getClass();
            Class<?> targetPOClass = targetPO.getClass();
            //这里是将targetMultiName进行展示
            Field declaredFieldDTO = targetDTOClass.getDeclaredField(targetMultiName);
            declaredFieldDTO.setAccessible(true);
            switch (locale) {
                case ZH_CN:
                    //获取PO的值
                    Field declaredFieldPO = targetPOClass.getDeclaredField(targetMultiName);
                    //获取DTO对象
                    declaredFieldPO.setAccessible(true);
                    //对DTO根据PO进行设置
                    declaredFieldDTO.set(targetDTO, declaredFieldPO.get(targetPO));
                    break;
                case EN_US:
                    //获取PO的值
                    Field declaredFieldPO2 = targetPOClass.getDeclaredField(targetMultiName + 2);
                    //获取DTO对象
                    declaredFieldPO2.setAccessible(true);
                    //对DTO根据PO进行设置
                    declaredFieldDTO.set(targetDTO, declaredFieldPO2.get(targetPO));
                    break;
                case ZH_TW:
                    //获取PO的值
                    Field declaredFieldPO3 = targetPOClass.getDeclaredField(targetMultiName + 3);
                    //获取DTO对象
                    declaredFieldPO3.setAccessible(true);
                    //对DTO根据PO进行设置
                    declaredFieldDTO.set(targetDTO, declaredFieldPO3.get(targetPO));
                    break;
                default:
                    break;
            }
            //防止没有抽取多语的情况下没有参照返回,默认情况下设置中文
            if (StringUtils.isBlank((String) declaredFieldDTO.get(targetDTO))) {
                //获取PO的值
                Field declaredFieldPO = targetPOClass.getDeclaredField(targetMultiName);
                //获取DTO对象
                declaredFieldPO.setAccessible(true);
                //对DTO根据PO进行设置
                declaredFieldDTO.set(targetDTO, declaredFieldPO.get(targetPO));
            }
        } catch (NoSuchFieldException e) {
            log.error("查询当前字段--->{}不存在{},", targetMultiName, e);
        } catch (IllegalAccessException e) {
            log.error("查询字段--->{}多语时发生非法状态异常{},", targetMultiName, e);
        } catch (Exception e) {
            log.error("查询字段{}多语时发生错误{},", targetMultiName, e);
        } catch (Throwable throwable) {
            log.error("查询多语言字段{}发生未知错误{}", targetMultiName, ThrowableUtil.stackTraceToString(throwable));
        }
    }
 
    /**
     * 更新多语字段
     *
     * @param targetDTO     需要转换的字段
     * @param targetPO      数据库PO
     * @param fieldName     多语字段
     * @param MultiLangSize 多语字段的数量
     */
    public static void updateMultiLang(Object targetDTO, Object targetPO, String fieldName, Integer MultiLangSize) {
        try {
            Class<?> targetDTOClass = targetDTO.getClass();
            Class<?> targetPOClass = targetPO.getClass();
 
            Field dtoClassField = targetDTOClass.getDeclaredField(fieldName);
            dtoClassField.setAccessible(true);
            if (StringUtils.isNotBlank((String) dtoClassField.get(targetDTO))) {
                Field poClassField = targetPOClass.getDeclaredField(fieldName);
                poClassField.setAccessible(true);
                poClassField.set(targetPO, dtoClassField.get(targetDTO));
            }
            for (int i = 2; i <= MultiLangSize; i++) {
                Field dtoClassField2 = targetDTOClass.getDeclaredField(fieldName + i);
                dtoClassField2.setAccessible(true);
                if (StringUtils.isNotBlank((String) dtoClassField2.get(targetDTO))) {
                    Field poClassField2 = targetPOClass.getDeclaredField(fieldName + i);
                    poClassField2.setAccessible(true);
                    poClassField2.set(targetPO, dtoClassField2.get(targetDTO));
                }
            }
        } catch (NoSuchFieldException e) {
            log.error("更新当前字段--->{}不存在{},", fieldName, e);
        } catch (IllegalAccessException e) {
            log.error("更新字段--->{}多语时发生非法状态异常{},", fieldName, e);
        } catch (Exception e) {
            log.error("更新字段{}多语时发生错误{},", fieldName, e);
        } catch (Throwable throwable) {
            log.error("更新多语言字段{}发生未知错误{}", fieldName, ThrowableUtil.stackTraceToString(throwable));
        }
    }
 
    /**
     * 获取本地的语言,默认中文
     * en_US  英文
     * zh_CN  简体中文
     * zh_TW  繁体中文
     *
     * @return
     */
    public static final String getLocale() {
        String locale = InvocationInfoProxy.getLocale();
        return StringUtils.isEmpty(locale) ? "zh_CN" : locale;
    }
}

The core idea of ​​this tool class is

  • Use Field’s get method to obtain attribute values

  • Field’s set method to set attributes

//Assign a value to a variable and assign a value to a field of the object object

f.set(object, value);

//Get an instance of the Field class Then you can call the method

//Method: get(Object obj) returns the value of the field represented by this Field on the specified object obj

The above is the detailed content of How to assign values ​​to object properties using Java reflection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete