java反射动态获取对象和塞入对应的值

/**
     * 为指定对象的指定属性动态赋予指定值
     *
     * @param obj       指定对象
     * @param fieldName 指定属性
     * @param value     指定值
     * @return obj      返回对象
     */
    public static Object dynamicSetValue(Object obj, String fieldName, Object value) {
        try {
            // 取属性首字母转大写
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            // set方法名
            String setMethodName = "set" + firstLetter + fieldName.substring(1);
            // 获取属性
            Field field = obj.getClass().getDeclaredField(fieldName);
            // 获取set方法
            Method setMethod = obj.getClass().getDeclaredMethod(setMethodName, field.getType());
            // 通过set方法动态赋值
            setMethod.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 动态获取指定对象指定属性的值
     *
     * @param obj       指定对象
     * @param fieldName 指定属性
     * @return 属性值
     */
    public static Object dynamicGetValue(Object obj, String fieldName) {
        try {
            // 取属性首字母转大写
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            // get方法名
            String getMethodName = "get" + firstLetter + fieldName.substring(1);
            // 获取get方法
            Method getMethod = obj.getClass().getDeclaredMethod(getMethodName);
            // 动态取值
            return getMethod.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值