Reference links:
https://developer.aliyun.com/ask/62145?spm=a2c6h.13159736
https://www.cnblogs.com/DFX339/p/9945771.html
problem analysis:
//判断1 : 这里会返回 true
User user = null;
if(user == null){
return true;
}else{
return false;
}
//判断2 : 这里会返回 false
User user = new User();
if(user == null){
return true;
}else{
return false;
}
原因: User user = new User(); 这时候已经创建了一个对象,所以user不会为null
The above example is relatively simple, at a glance, it seems there is no problem.
" But in fact, when the object you need to determine the object to pass over the tip, simply use the object == null is not enough to judge, because the front will pass over the object is to determine 2 look like.
Object is not null, but all the properties of the object are null . [except except boolean type, and a sequence of values, there may be other special values please add yo ~] "
"" Content identified if not clear, please refer to previous blog: https://www.cnblogs.com/DFX339/p/9896476.html
Solutions:
Util create classes, properties of the object using the reflection of the determination
note:
When you need to determine whether the Java object is null, you can start to judge by obj == null, if obj is not equal to null, then decide whether further determined whether all the attributes of obj are null according to business needs.
public boolean objCheckIsNull(Object object){
Class clazz = (Class)object.getClass(); // 得到类对象
Field fields[] = clazz.getDeclaredFields(); // 得到所有属性
boolean flag = true; //定义返回结果,默认为true
for(Field field : fields){
field.setAccessible(true);
Object fieldValue = null;
try {
fieldValue = field.get(object); //得到属性值
Type fieldType =field.getGenericType();//得到属性类型
String fieldName = field.getName(); // 得到属性名
System.out.println("属性类型:"+fieldType+",属性名:"+fieldName+",属性值:"+fieldValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
if(fieldValue != null){ //只要有一个属性值不为null 就返回false 表示对象不为null
flag = false;
break;
}
}
return flag;
}