判断一个对象的各个属性是否为空的方法

本文介绍了一种通过反射机制遍历对象的所有属性,并利用自定义工具类进行非空判断的方法,确保对象在使用前各属性的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断一个对象的各个属性是否为空的方法:

 

        //查询出对象所有的属性
        Field[] fields = obj.getClass().getDeclaredFields();
        //用于判断所有属性是否为空,如果参数为空则不查询
        boolean flag = false;
        for (Field field : fields) {
            //不检查 直接取值
            field.setAccessible(true);
            try {
                if(StringUtils.isNotNull(field.get(obj))) {
                    //不为空
                    flag = true;
                    //当有任何一个参数不为空的时候则跳出判断直接查询
                    break;
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

其中 obj 为需要判断的对象。StringUtils 是手动写的一个工具类。其中关于非空判断的代码为:

public class StringUtils {
   public final static boolean isNull(Object[] objs) {
		if (objs == null || objs.length == 0)
			return true;
		return false;
	}
	public final static boolean isNull(Object obj) {
		if (obj == null || isNull(obj.toString())){
			return true;
		}
		return false;
	}

	public final static boolean isNull(Integer integer) {
		if (integer == null || integer == 0)
			return true;
		return false;
	}

	public final static boolean isNull(Collection collection) {
		if (collection == null || collection.size() == 0)
			return true;
		return false;
	}

	public final static boolean isNull(Map map) {
		if (map == null || map.size() == 0)
			return true;
		return false;
	}

	public final static boolean isNull(String str) {
		return str == null || "".equals(str.trim())
				|| "null".equals(str.toLowerCase());
	}

	public final static boolean isNull(Long longs) {
		if (longs == null || longs == 0)
			return true;
		return false;
	}

	public final static boolean isNotNull(Long longs) {
		return !isNull(longs);
	}

	public final static boolean isNotNull(String str) {
		return !isNull(str);
	}

	public final static boolean isNotNull(Collection collection) {
		return !isNull(collection);
	}

	public final static boolean isNotNull(Map map) {
		return !isNull(map);
	}

	public final static boolean isNotNull(Integer integer) {
		return !isNull(integer);
	}

	public final static boolean isNotNull(Object[] objs) {
		return !isNull(objs);
	}
	public final static boolean isNotNull(Object obj) {
		return !isNull(obj);
	}
 
}

备存以后方便使用。

 

最近在整理个人公众号,大家可以来关注关注,指导一下哦

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值