简体   繁体   中英

optimize java code and how to make it look good

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());
        }

        ........

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()
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM