# Java判空的方法的使用 ### 一. 字符串的判空 #### 1.使用org.springframework.util.StringUtils工具类判断字符串为空指针,空数据,和带空格 ==StringUtils.hasText()== \`\`\`java @Test public void test01(){ String s1 = null; // null对象 String s2 = ""; // 空串 String s3 = " "; // 带空格 System.out.println("s1:"+ StringUtils.hasText(s1)); System.out.println("s2:"+ StringUtils.hasText(s2)); System.out.println("s3:"+ StringUtils.hasText(s3)); } /\* 控制台输出: s1:false s2:false s3:false \*/ \`\`\` #### 2.判断字符串为空指针和空数据: StringUtils.isEmpty() ==StringUtils.isEmpty()== : 已弃用(可用hasText代替) #### 3.判断字符串为空指针和空数据: s == null \|\|s.length() \<= 0 \`\`\`java public static void main(String\[\] args) { String s=null; if(s == null \|\| s.length() \<= 0){ System.out.println("执行s为空------------"); } String str = null; // 或者 str = ""; if (str == null \|\| str.length() == 0 \|\| str.trim().length() == 0) { // 字符串为空或null } } \`\`\` #### 4. 判断字符串为空数据 : "".equals(str); #### 5. 使用 Apache Commons Lang3 提供的 判断字符串是否为空或者只包含空格字符 StringUtils 提供了许多字符串操作相关的方法,其中比较常用的包括 isEmpty、isNotEmpty、isBlank 和 isNotBlank \`\`\`java import org.apache.commons.lang3.StringUtils; if (StringUtils.isBlank(str)) { // 字符串为空或者只包含空格字符 } if (str == null \|\| str.isEmpty()) { // 字符串为空 } \`\`\` #### 6. 使用正则表达式判断字符串是否为空或只包含空格 \`\`\`java String str = " "; if (str.matches("\\\\s\*")) { // 字符串为空或只包含空格 } \`\`\` #### 二. 集合的判空 #### 1.null直接显式判断空指针+list.isEmpty判断是否为空 \`\`\`java @Test public void nullCollectionUnderRawTest() { List list1 = null; if (null == list1) { logger.info("lsit1 is null"); } else if (list1.isEmpty()) { logger.info("list1 is empty"); } else { logger.info("list1 is:{}", list1); } } \`\`\` #### 2. Objects.isNull隐式判断空指针+list.isEmpty判断是否为空 \`\`\`java /\*\* \* 集合类型:使用Objects判断空指针 \*/ @Test public void nullCollectionUnderObjectsTest() { List list1 = null; if (Objects.isNull(list1)) { logger.info("lsit1 is null"); } else if (list1.isEmpty()) { logger.info("list1 is empty"); } else { logger.info("list1 is:{}", list1); } } \`\`\` #### 3. CollectionUtils.isEmpty工具判断空指针和空 ==CollectionUtils.isEmpty:== 空指针和空数据都为false 引入依赖 \`\`\`xml org.apache.commons commons-collections4 4.4 \`\`\` \`\`\`java /\*\* \* 集合类型:使用CollectionUtils判断空指针和空数据 \*/ @Test public void nullUnderCollectionUtilsTest() { List list1 = null; if (CollectionUtils.isEmpty(list1)) { logger.info("\>\>\>\>\>\>\>\>\>\>var1 is null or empty"); } else { logger.info("\>\>\>\>\>\>\>\>\>\>var1 is:{}", list1); } } \`\`\` ### 三. 包装类判空 判断是否为0 \`\`\`java Long a = 0; if(a.longValue() == 0){ } \`\`\`