该工具类主要用于处理特定类型的属性的默认值,如默认Double类型属性为空时赋值为0的工具类

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.spi.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
* @ClassName ObjectFiledsUtil
* @Description 类属性值工具类
* @Author Leslie Hwang
* @Email [email protected]
* @Date 2021/5/10 下午4:41
**/
@Slf4j
public class ObjectFiledsUtil {

/**
* @description: 处理实体类属性为Double类型的字段为null时默认赋值为0
* @param: [object]
* @return: java.lang.Object
* @author: leslie
* @email: [email protected]
* @date: 2021/5/11
*/
public static Object objectDoubleTypeFiledDeal(Object object) throws NoSuchMethodException {
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getType().getName().equals("java.lang.Double")){
field.setAccessible(true);
String key = field.getName();// 获取属性名
String method = key.substring(0,1).toUpperCase()+key.substring(1);// 将属性首字符大写,方便get & set 方法

//获取属性值
Method getMethod = object.getClass().getMethod("get"+method);// 获取 get 方法
Object value = null;
try {
value = getMethod.invoke(object);// 通过 get 获取值
} catch (IllegalAccessException e) {
log.error("IllegalAccessException Error Info {}", e.getMessage(), e);
} catch (InvocationTargetException e) {
log.error("InvocationTargetException Error Info {}", e.getMessage(), e);
}

if (NullOrEmpty(value)){
//属性赋值
Method setMethod = object.getClass().getMethod("set" + method, Double.class); //获取set方法
try {
setMethod.invoke(object, 0.0);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

}
return object;
}

public static boolean NullOrEmpty(Object value){
if (value == null || "".equals(value)) {
return true;
} else {
return false;
}
}

}