/**
* @description: 判断对象的属性值是否为空,如果类型是包装类并且为空,就为其赋值对应基本类型的默认值
* @param model 需要检查的对象
* @author: duyq
* @date: 2019/8/7 9:50
* @return: T
*/
public static<T> T checkProperty(T model){
Class<?> clazz = model.getClass();
Field[] fields = clazz.getDeclaredFields();
for(Field field : fields){
try {
//属性名
String fieldName = field.getName();
if(fieldName.equals("serialVersionUID")) continue;
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method getMethod = clazz.getMethod(getMethodName);
//获取属性值
Object obj = getMethod.invoke(model);
if(obj == null || "".equals(obj.toString().trim())){
//属性类型
String type = field.getGenericType().toString();
String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method setMethod = clazz.getDeclaredMethod(setMethodName,field.getType());
switch (type) {
case "class java.lang.Integer":
setMethod.invoke(model, 0);
break;
case "class java.lang.Long":
setMethod.invoke(model, 0L);
break;
case "class java.lang.String":
setMethod.invoke(model, new Object[]{null});
break;
case "class java.lang.Float":
setMethod.invoke(model, 0.0f);
break;
case "class java.lang.Double":
setMethod.invoke(model, 0.0d);
break;
default:
setMethod.invoke(model, obj);
break;
}
}
}catch (Exception e) {
logger.info("set property is failure : {}",model.toString());
}
}
return model;
}
反射获取对象的属性并为其赋值
最新推荐文章于 2023-01-04 20:06:05 发布