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++) {
            user.setValue(user, "month"+(i+1),"aaa"+(i+1));
        }

        System.out.println(user);
        System.out.println(user.getValue(user,"month12"));
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值