current position:Home>Dynamically set and get values ​​for fields in java field entity classes

Dynamically set and get values ​​for fields in java field entity classes

2022-11-24 22:48:52JoyceYoungbjt

import java.lang.reflect.Field;

public class User {
    
    private String month1;
    private String month2;
    private String month3;
    private String month4;
    private String month5;
    private String month6;
    private String month7;
    private String month8;
    private String month9;
    private String month10;
    private String month11;
    private String month12;


    /** * Dynamically call the entity classset方法 * * @param dto 实体 * @param name 动态字段 * @param value 值 * @throws Exception */
    public void setValue(User dto, String name, Object value) {
    
        try {
    
            Field[] fields = dto.getClass().getDeclaredFields();
            for (Field field : fields) {
    
                field.setAccessible(true);
                if (field.getName().equals((name))) {
    
                    field.set(dto, value);
                }
            }
        } catch (Exception e) {
    
            e.printStackTrace();
        }
    }

    /** * Dynamically call the entity'sget方法(注意返回值) * * @param dto 实体 * @param name 动态字段 * @throws Exception */
    public Object getValue(User dto, String name) {
    
        try {
    
            Field declaredField = dto.getClass().getDeclaredField(name);
            return declaredField.get(dto);
        } catch (NoSuchFieldException | IllegalAccessException e) {
    
            return null;
        }
    }
}

The above is a simple example,In actual use, change the first parameter to dynamic

使用:

public class Test4 {
    
    public static void main(String[] args) {
    

        User user = new User();

        for (int i = 0; i < 12; i++) {
    
            user.setValue(user, "month"+(i+1),"aaa"+(i+1));
        }

        System.out.println(user);
        System.out.println(user.getValue(user,"month12"));
    }
}

copyright notice
author[JoyceYoungbjt],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/328/202211242246194046.html

Random recommended