pojo类不能有默认值怎么办,使用Bean Utils填充POJO时为字段设置默认值

I am trying to populate the fields of a POJO using BeanUtilsBean.populate(object, fieldNameVSfieldValueMap) method.

My POJO looks like :

class POJO{

Integer intField;

Double doubleField

String str;

}

Currently I have a HashMap that contains a map between the field name and field value.

Now with the following code:

POJO obj = new POJO();

Map map = new HashMap<>();

map.put("intField", "1");

map.put("doubleField", "1.1");

BeanUtilsBean.populate(obj, map)

With the above code in my POJO object obj, the fields intField and doubleField get populated with the values 1 and 1.1 respectively which is as expected.

The problem with this is that, the string field str get null assigned to it as there was no entry in the hashmap for str and null is default value for String.

But I want was an explicit way to set my custom value to a field when they are not mentioned in the map.

For this example lets say I want to set str to "john" as there is not entry for str in the map.

Edit 1:

And also that should be specific to the field type. So if there are other fields in POJO and they are of String type, then for all those String fields, for whom entry is not there in the Map should be populated with John.

Edit 2: The POJO is defined in a different project that I dont have commit access to, so set default values in the POJO itself is not a solution to me.

解决方案

Try using the org.apache.commons.beanutils.BeanUtilsBean class with aid of the org.apache.commons.beanutils.ConvertUtilsBean class

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值