前言
利用反射实现空字段属性赋值,例如:两个结构相似的对象A和B,利用对象B补全对象A里属性值为空的字段,并返回一个完整的对象A。
一、获取对象中属性值为空的字段集合
代码如下(示例):
/**
* @Title: getNullFields
* @Description: 获取值为空的属性字段集合
*/
public static List<Field> getNullFields(Object source) throws IllegalAccessException {
List<Field> nullFields = Lists.newArrayList();
Field[] fields = source.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(source);
if (value == null) {
nullFields.add(field);
}
}
return nullFields;
}
二、赋值空字段属性值
代码如下(示例):
Object A = new Object(); //具体的java对象
Object B = new Object(); //具体的java对象
List<Field> nullFields = getNullFields(A);
if(!CollectionUtils.isEmpty(nullFields)) {
for(Field field : nullFields) {
Object obj = FieldUtils.readField(B,field.getName(),true);
field.set(A, obj);
}
}