使用Bean Utils填充POJO时为字段设置默认值 [英] Set default value for a field while populating POJO using Bean Utils

查看:885
本文介绍了使用Bean Utils填充POJO时为字段设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用BeanUtilsBean.populate(object, fieldNameVSfieldValueMap)方法填充POJO的字段.

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

我的POJO如下:

class POJO{
  Integer intField;
  Double doubleField
  String str;
}

当前,我有一个HashMap,其中包含字段名称和字段值之间的映射.

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

现在输入以下代码:

POJO obj = new POJO();
Map<String,String> map = new HashMap<>();
map.put("intField", "1");
map.put("doubleField", "1.1");
BeanUtilsBean.populate(obj, map)

在我的POJO对象obj中使用上面的代码,字段intField和doubleField分别填充了期望的值1和1.1.

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.

此问题是,字符串字段str分配了null值,因为哈希表中没有str项,而null是String的默认值. 但是,我想提供一种明确的方式来将我的自定义值设置为字段(当地图中未提及它们时). 对于此示例,可以说我想将str设置为"john",因为在地图中没有str的条目. 并且这也应该特定于字段类型.因此,如果POJO中还有其他字段,并且它们是String类型的,那么对于所有那些Map中没有在其中输入的String字段,都应使用John填充.

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.

POJO是在我没有提交访问权限的另一个项目中定义的,因此在POJO本身中设置默认值对我来说不是解决方案.

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.

推荐答案

尝试在org.apache.commons.beanutils.ConvertUtilsBean类的帮助下使用org.apache.commons.beanutils.BeanUtilsBean类

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

这篇关于使用Bean Utils填充POJO时为字段设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆