Java各种数据类型判断是否为空或者为null方法

绝地灬酷狼 2022-11-05 13:52 880阅读 0赞

Java 各种数据类型判断是否为空或者为null方法

开发中经常对各种数据进行判断是否为空或者为null 对数据进行校验

最近开发中经常老是使用各种方式进行判断,这里就对常见的数据类型判断方法进行一个统计汇总,如果有错就请帮忙指出下。

对象类型 判断 Object org.apache.commons.lang3.ObjectUtils;

org.apache.commons.lang3.StringUtils;

  1. Object o = new Object();
  2. if (o !=null){
  3. System.out.println("not null");
  4. }
  5. //还可以使用
  6. Object obj =null;
  7. String s = ObjectUtils.toString(obj, "");
  8. System.out.println(s+"1");
  9. if (StringUtils.isBlank(s)){
  10. System.out.println("空");
  11. }else {
  12. System.out.println("不为空");
  13. }

List 判断 是否为空 这个包 org.springframework.util.CollectionUtils;

  1. List<String> list = new ArrayList<>();
  2. boolean empty = CollectionUtils.isEmpty(list);
  3. if (empty) {
  4. System.out.println("空");
  5. }else {
  6. System.out.println("不为空");
  7. }

Map 判断 是否为空 org.springframework.util.CollectionUtils;

  1. HashMap<String, Object> map = new HashMap<>(16);
  2. if (CollectionUtils.isEmpty(map)){
  3. System.out.println("空");
  4. }else {
  5. System.out.println("不为空");
  6. }

String 判断 是否为空 org.apache.commons.lang3.StringUtils;

StringUtils 中有 俩个 方法 isNotEmpty 和 isNotBlank 基本是一样的

就是 isNotBlank 增加了空格\t \n \f \r 这些的判断忽略

  1. String str = "str";
  2. if (StringUtils.isNotEmpty(str)){
  3. }
  4. if (StringUtils.isNotBlank(str)){
  5. }

基本类型 包装类型 都可以 使用以下

Integer都可以转化成String 然后判断

  1. Integer num =1;
  2. if (StringUtils.isNotEmpty(String.valueOf(num))){
  3. System.out.println("不为空");
  4. }

Long 都可以转化成String 然后判断

  1. Long longNum =1L;
  2. if (StringUtils.isNotEmpty(String.valueOf(longNum))){
  3. System.out.println("不为空");
  4. }

发表评论

表情:
评论列表 (有 0 条评论,880人围观)

还没有评论,来说两句吧...

相关阅读