能适配所有类型的:
类似这个效果的...自己写了个类,只能对string判断:
public class BeanUtils {
public static boolean checkFieldValueNull(Object bean) {
boolean result = true;
if (bean == null) {
return true;
}
Class<?> cls = bean.getClass();
Method[] methods = cls.getDeclaredMethods();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
try {
String fieldGetName = parGetName(field.getName());
if (!checkGetMet(methods, fieldGetName)) {
continue;
}
Method fieldGetMet = cls.getMethod(fieldGetName, new Class[]{});
Object fieldVal = fieldGetMet.invoke(bean, new Object[]{});
if (fieldVal != null) {
if ("".equals(fieldVal)) {
result = true;
} else {
result = false;
}
}
} catch (Exception e) {
continue;
}
}
return result;
}
/**
* 拼接某属性的 get方法
*
* @param fieldName
* @return String
*/
public static String parGetName(String fieldName) {
if (null == fieldName || "".equals(fieldName)) {
return null;
}
int startIndex = 0;
if (fieldName.charAt(0) == '_')
startIndex = 1;
return "get"
+ fieldName.substring(startIndex, startIndex + 1).toUpperCase()
+ fieldName.substring(startIndex + 1);
}
/**
* 判断是否存在某属性的 get方法
*
* @param methods
* @param fieldGetMet
* @return boolean
*/
public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
for (Method met : methods) {
if (fieldGetMet.equals(met.getName())) {
return true;
}
}
return false;
}
}
其实不用那么麻烦,只用定义一个方法,然后使用下面的代码片段来判断字段是否为空:
for (Field f : obj.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (f.get(obj) == null) { //判断字段是否为空,并且对象属性中的基本都会转为对象类型来判断
......
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。