Set default value for a field while populating POJO using Bean Utils

DockYard :

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<String,String> 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.

Zeus :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326459&siteId=1