代码review的时候居然发现犯这么低级的错误,判空方法严重错误
String strNull = null; str引用为空,对象还未创建
String strEmpty = ""; str应用一个空串,栈空间中已经分配内存空间
//先判断是不是对象,如果是,再判断是不是空字符串
if(strNull == null || strEmpty.equals(" ")){
// do something
}
//我们这里是声明的strEmpty,如果我们不知道strEmpty是否已经声明呢
//所以,很有可能strEmpty没有创建,那么Nullpointer Exception就发生了
//因此,我们要用一个已知的变量去equals一个未知的变量
if(strNull == null || "".equals(strEmpty)){
// do something
}
//但是更好的方法是我们用apache的第三方jar包
//apache commons 有一个StringUtils里面包含了判空方法,其源代码如下
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
//isEmpty(String str) 我们同时注意到如果str为Null 同样有空指针错误
//好在ObjectUtil里面重写了toString方法,我们查看其源代码如下
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
//所以,如果怕导致空指针异常我们只需要先调用toString方法
//然后调用isEmpty方法即可,例子如下
package com.test;
import org.apache.commons.lang.StringUtils;
/**
*
* @author kevin.yang
*/
public class StringUtilsTest {
public static void main(String[] args){
StringUtilsTest testNull = null;
StringUtilsTest test = new StringUtilsTest();
boolean isNull ;
//对象不为空
isNull = StringUtils.isEmpty(test.toString());
System.out.println("对象不为空||test.toString():"+test.toString());
//对象为空
isNull = StringUtils.isEmpty(testNull.toString());
System.out.println("对象为空||testNull.toString()"+testNull.toString());
}
}
//我们可以看到控制台报空指针了
对象不为空||test.toString():com.test.StringUtilsTest@de6ced
Exception in thread "main" java.lang.NullPointerException
at com.test.StringUtilsTest.main(StringUtilsTest.java:18)
Java Result: 1
//原因在与testNull 对象为空,其调用jdk的toString()方法必然报错
//一方面我们可以自己重写toString方法,我采用的是
//调用lang包下的ObjectUtils下的toString方法
package com.test;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.ObjectUtils;
/**
*
* @author kevin.yang
*/
public class StringUtilsTest {
public static void main(String[] args){
StringUtilsTest testNull = null;
StringUtilsTest test = new StringUtilsTest();
boolean isNull ;
//对象不为空
isNull = StringUtils.isEmpty(test.toString());
System.out.println("对象不为空||test.toString():"+test.toString());
//对象为空
//isNull = StringUtils.isEmpty(testNull.toString());
//System.out.println("对象为空||testNull.toString()"+testNull.toString());
//调用ObjectUtils下的方法
String obNull = ObjectUtils.toString(testNull);
System.out.print("obNull:"+obNull);
System.out.println("obNull--->isEmpty():"+StringUtils.isEmpty(obNull));
}
}
//我们看看控制台的输出
对象不为空||test.toString():com.test.StringUtilsTest@de6ced
obNull:obNull--->isEmpty():true
这样我们就解决了为空的问题
commons包下还有很多很好用的工具,可以到网上下载他的jar包及帮助