Set default value for a field while populating POJ

2020-04-17 07:19发布

问题:

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.

回答1:

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



回答2:

Basically you could do:

Map<String, String> map = new HashMap<>() {  // new HashMap<String, String> perhaps
    @Override
    public String get(Object key} {
        return super.getOrDefault(key, "john");
    }
}

If you want different defaults per field, use a local map, prefilled with defaults.

Then you should make your own class.