Java插入数据库,自动填充策略(给类及其所有父类赋值)
/**
* 给类及其所有父类赋值
* @param object
*/
public static void converEmptyNullToString(Object object) {
try {
Class cl = object.getClass();
List<Field> fields = new ArrayList<>();
Object obj = object;
while (cl != null){
Field[] fs = obj.getClass().getDeclaredFields();
fields = new ArrayList<>(Arrays.asList(fs));
for (Field f : fields) {
f.setAccessible(true);
Object val = f.get(obj);
String type = f.getType().toString();
if (null == val){
if (type.endsWith("String")){
f.set(object,"");
}
if (type.endsWith("BigDecimal")){
f.set(object,BigDecimal.ZERO);
}
if (type.endsWith("Integer")){
f.set(object,0);
}
if (type.endsWith("Date")){
f.set(object,DateUtils.dateStrToDate("1900-01-01"));
}
}
}
cl = cl.getSuperclass();
if (null != cl){
obj = cl.newInstance();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}