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

查看:60
本文介绍了使用 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 看起来像:

My POJO looks like :

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 被分配给它,因为在哈希图中没有 str 的条目,而 null 是字符串的默认值.但是我想要一种明确的方法,当地图中没有提到它们时,将我的自定义值设置为字段.对于这个例子,假设我想将 str 设置为john",因为地图中没有 str 的条目.而且这应该特定于字段类型.因此,如果 POJO 中还有其他字段并且它们是 String 类型的,那么对于所有这些 String 字段,在 Map 中没有条目的字段应该用 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.

编辑 2: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天全站免登陆