利用反射获取对象属性,遍历进行判断
/**
* @param object 需要判断的对象
* @param fieldList 需要判断的部分属性
* @return
*/
public static boolean checkObjFieldIsNull(Object object, List<String> fieldList) throws IllegalAccessException {
if (object == null) {
return true;
}
for (Field field : object.getClass().getDeclaredFields()) {
// 私有属性设置为可见
field.setAccessible(true);
// 如果需要进行非空判断
if(fieldList.contains(field.getName())){
//属性值
Object obj = field.get(object);
// if(obj == null || StringUtils.isNull(obj.toString())){
if (obj == null || obj.toString().isEmpty()){
System.out.println(field.getName() + " can not be null!");
return true;
}
}
}
return false;
}
测试:
public static void main(String[] args) {
//需要非空判断的属性
String[] fieldArray = new String[]{"name","age"};
List<String> fieldList = Arrays.asList(fieldArray);
User user = new User("huahua",15,"fm");
try {
boolean b = checkObjFieldIsNull(user, fieldList);
System.out.println(b);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
实体类:
/**
* @author Administrator
* @date 2019-08-08 17:41
*/
public class User{
private String name;
private Integer age;
private String gen;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGen() {
return gen;
}
public void setGen(String gen) {
this.gen = gen;
}
public User(String name, Integer age, String gen) {
this.name = name;
this.age = age;
this.gen = gen;
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public User(String name) {
this.name = name;
}
}