优化java代码以及如何使其外观良好

优化java代码以及如何使其外观良好,java,optimization,Java,Optimization,我有一段代码,它总是被使用,但看起来非常冗余,我能做些什么来避免冗余 if(CommonUtil.isNull(second.getProvince())) { second.setProvince(first.getProvince()); } if(CommonUtil.isNull(second.getCity())) { second.setCity(first.getCity());

我有一段代码,它总是被使用,但看起来非常冗余,我能做些什么来避免冗余

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

        ........

由于您的对象看起来像远处的豆子,您可以看看java.beans.Introspector和BeanInfo

大致如下:

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

您可以在数据类中编写此方法,并使用一行代码对所有字段进行空控制。我的代码建议如下:

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;

}

您可以在循环中使用反射或lambdas。您可以使用,如果它不提供现成的忽略已设置的字段,您可以提供自己的转换器/映射器()。关于这种情况,我如何使用lambdas?多了解一下上下文就好了。例如,首先应用
的属性
然后用其他源覆盖它们如何?在您的情况下,这可能是不可能的,但如果是,则根本不需要检查空值。
second.copyIfNull(first)