-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
Expand file tree
/
Copy pathBeanUtils.java
More file actions
65 lines (58 loc) · 2.17 KB
/
BeanUtils.java
File metadata and controls
65 lines (58 loc) · 2.17 KB
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
package me.chanjar.weixin.common.util;
import com.google.common.collect.Lists;
import me.chanjar.weixin.common.annotation.Required;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <pre>
* bean操作的一些工具类
* Created by Binary Wang on 2016-10-21.
* </pre>
*
* @author <a href="https://github.com/binarywang">binarywang(Binary Wang)</a>
*/
public class BeanUtils {
private static Logger log = LoggerFactory.getLogger(BeanUtils.class);
/**
* 检查bean里标记为@Required的field是否为空,为空则抛异常
*
* @param bean 要检查的bean对象
*/
public static void checkRequiredFields(Object bean) throws WxErrorException {
List<String> requiredFields = Lists.newArrayList();
List<Field> fields = new ArrayList<>(Arrays.asList(bean.getClass().getDeclaredFields()));
fields.addAll(Arrays.asList(bean.getClass().getSuperclass().getDeclaredFields()));
for (Field field : fields) {
try {
boolean isAccessible = field.isAccessible();
field.setAccessible(true);
if (field.isAnnotationPresent(Required.class)) {
// 两种情况,一种是值为null,
// 另外一种情况是类型为字符串,但是字符串内容为空的,都认为是没有提供值
boolean isRequiredMissing = field.get(bean) == null
|| (field.get(bean) instanceof String
&& StringUtils.isBlank(field.get(bean).toString())
);
if (isRequiredMissing) {
requiredFields.add(field.getName());
}
}
field.setAccessible(isAccessible);
} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
log.error(e.getMessage(), e);
}
}
if (!requiredFields.isEmpty()) {
String msg = String.format("必填字段【%s】必须提供值!", requiredFields);
log.debug(msg);
throw new WxErrorException(msg);
}
}
}