0

I have a piece of code, it's always used but it looked very redundant , and what can I do for sidestepping redundancy.

        if(CommonUtil.isNull(second.getProvince())) {
            second.setProvince(first.getProvince());
        }

        if(CommonUtil.isNull(second.getCity())) {
            second.setCity(first.getCity());
        }

        if(CommonUtil.isNull(second.getDistrict())) {
            second.setDistrict(first.getDistrict());
        }

        if(CommonUtil.isNull(second.getAddress())) {
            second.setAddress(first.getAddress());
        }

        ........
NattyQ
  • 39
  • 5
  • 1
    You could use reflection or lambdas in a loop. – Peter Lawrey Mar 31 '16 at 08:46
  • 1
    You could use [Dozer](http://dozer.sourceforge.net/) and if it doesn't provide ignoring already set fields out of the box you can provide your own converter/mapper ([How can I tell Dozer to bypass mapping null or empty string values per field using the programming api?](http://stackoverflow.com/questions/19256952/how-can-i-tell-dozer-to-bypass-mapping-null-or-empty-string-values-per-field-usi)). – Thomas Mar 31 '16 at 08:52
  • how can I use lambdas, about this case? – NattyQ Mar 31 '16 at 09:46
  • A bit more about the context would be nice. For example how about applying the properties of `first` first, and then overwrite them with the other source? It may not be possible in your case but if it is, you wouldn't have to check for nulls at all. – biziclop Mar 31 '16 at 10:05

2 Answers2

0

As your objects look like beans from afar, you might have a look at java.beans.Introspector and BeanInfo.

Roughly along the lines of:

BeanInfo bi = Introspector.getBeanInfo(MyObjectClass.class);
for(PropertyDescriptor p : bi.getPropertyDescriptors()) {
    // perform null-check
    // invoke read on source object via read method delivered by p.getReadMethod()
    // write to target via method delivered by p.getWriteMethod()
}
mtj
  • 3,381
  • 19
  • 30
0

You can write this method in your data classes and do null control of all fields with one line of code. My code advice is like below:

public boolean copyIfNull(Object o)
{

        Class<?> clazz = this.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for(Field field : fields)
        {
        try {
            Object fieldValue = field.get(this);
            if (fieldValue == null)
            {
                field.set(this, field.get(o));
                return false;
            }
        }

        catch (Exception e) {
            System.err.println("Field value could not be obtained");
            e.printStackTrace();
            return false;
        }
        }


    return true;

}

And you will call this method in main like that:

second.copyIfNull(first)
Raptor
  • 187
  • 1
  • 2
  • 11