JAVA 封装一个工具类,将实例的里面的空值设为对应的默认值,比喻字符串类型就设为默认 "", Integer就设为0
示例代码:
/**
* 设置对象中所有空值属性为默认值。
*
* @param obj 待处理的对象。
*/
protected static void setDefaults(Object obj) {
Class<?> clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true); // 允许访问私有字段
try {
Object fieldValue = field.get(obj);
if (fieldValue == null) {
if (field.getType().isPrimitive() || field.getType() == String.class) {
// 对于基本类型和String,直接设置默认值
setDefaultValue(field, obj);
} else if (field.getType() == Integer.class || field.getType() == Integer.TYPE) {
// 对于Integer类型,设置默认值0
field.set(obj, 0);
} else if (field.getType() == Double.class || field.getType() == Double.TYPE) {
field.set(obj, 0.0);
} else if (field.getType() == Long.class || field.getType() == Long.TYPE) {
field.set(obj, 0L);
} else {
// 对于其他类型,不做处理
continue;
}
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to access field: " + field.getName(), e);
}
}
}
private static void setDefaultValue(Field field, Object obj) throws IllegalAccessException {
if (field.getType() == boolean.class || field.getType() == Boolean.class) {
field.setBoolean(obj, false);
} else if (field.getType() == byte.class || field.getType() == Byte.class) {
field.setByte(obj, (byte) 0);
} else if (field.getType() == char.class || field.getType() == Character.class) {
field.setChar(obj, '\u0000');
} else if (field.getType() == short.class || field.getType() == Short.class) {
field.setShort(obj, (short) 0);
} else if (field.getType() == int.class || field.getType() == Integer.class) {
field.setInt(obj, 0);
} else if (field.getType() == long.class || field.getType() == Long.class) {
field.setLong(obj, 0L);
} else if (field.getType() == float.class || field.getType() == Float.class) {
field.setFloat(obj, 0.0f);
} else if (field.getType() == double.class || field.getType() == Double.class){
field.setDouble(obj, 0.0);
}else if (field.getType() == String.class){
field.set(obj, "");
}
}
使用:
public static void main(String[] args) {
CZKInfoDTO dto=new CZKInfoDTO();
setDefaults(dto);
System.out.println(JSON.toJSONString(dto));
}
运行结果:
而使用设置得到的结果: