java中,String 类下的 isEmpty( ) 返回的只是 字符串的长度是否为0,如果 字符串为null 就会直接报空指针。源码如下:
public boolean isEmpty() { return count == 0; }
android中,TextUtils.isEmpty(要判断的字符串) 会对 null 和长度进行判断,所以不会报空指针。源码如下:
public static boolean isEmpty(@Nullable CharSequence str) { if (str == null || str.length() == 0) return true; else return false; }
Android开发中,我们经常使用TextUtils.isEmpty()来判断字符串是否为null或者空字符串,防止出现空指针异常,有一天执行报出了空指针异常 。如下
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference满头黑线
查看源码
/** * Returns true if the string is null or 0-length. * @param str the string to be examined * @return true if str is null or zero length */ public static boolean isEmpty(CharSequence str) { if (str == null || str.length() == 0) return true; else return false; }得出一般情况下使用是没问题的。
现在我们考虑这样一种情况:假设实体参数有一个属性 name,String类型。后台在响应这个属性到手机端的时候,是这样赋值的 name = null + “”,这样就会报错。
参考:小知识–TextUtils.isEmpty与String.isEmpty
使用TextUtils.isEmpty()遇到的坑