java field 实体类中字段的动态设置值和获取值

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;


    /**
     * 动态调用实体类的set方法
     *
     * @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();
        }
    }

    /**
     * 动态调用实体的get方法(注意返回值)
     *
     * @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;
        }
    }
}

以上是简单示例,实际使用时把第一个参数改为动态的

使用:

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

        User user = new User();

        for (int i = 0; i < 12; i++) {
          //设置用户表 循环12月  值为aaa1、aaa2、aaa3---aaa12
            user.setValue(user, "month"+(i+1),"aaa"+(i+1));
        }
         System.out.println(user);
         //获取用户表12月  值
        System.out.println(user.getValue(user,"month12"));
    }
}

你可能感兴趣的:(java,开发语言)