java 判断对象是否为空「建议收藏」

java 判断对象是否为空「建议收藏」java中如何判断对象是否为空呢,特别是一个weizhi

大家好,又见面了,我是你们的朋友全栈君。

java 中如何判断对象是否为空呢,特别是一个未知的对象?

下面是一个通用的方法,判断字符串是否为空,集合是否为空,数组是否为空:

/**
	 * 判断对象或对象数组中每一个对象是否为空: 对象为null,字符序列长度为0,集合类、Map为empty
	 * 
	 * @param obj
	 * @return
	 */
	public static boolean isNullOrEmpty(Object obj) {
		if (obj == null)
			return true;

		if (obj instanceof CharSequence)
			return ((CharSequence) obj).length() == 0;

		if (obj instanceof Collection)
			return ((Collection) obj).isEmpty();

		if (obj instanceof Map)
			return ((Map) obj).isEmpty();

		if (obj instanceof Object[]) {
			Object[] object = (Object[]) obj;
			if (object.length == 0) {
				return true;
			}
			boolean empty = true;
			for (int i = 0; i < object.length; i++) {
				if (!isNullOrEmpty(object[i])) {
					empty = false;
					break;
				}
			}
			return empty;
		}
		
		return false;
	}

上述方法运用了递归,当对象是数组时又调用自身.

测试:

@Test
	public void test_isNullOrEmpty(){
		String input1=null;
		String input3="";
		String input4=" ";
		String input5="a";
		String input6="   ";
		String[] strs1 = new String[] { "a" };
		String[] strs2 = new String[] { "", "" };
		String[] strs3 = new String[] { "", "c" };
		String[] strs4 = new String[] {};
		org.junit.Assert.assertEquals(true, ValueWidget.isNullOrEmpty(input1));
		org.junit.Assert.assertEquals(true, ValueWidget.isNullOrEmpty(input3));
		org.junit.Assert.assertEquals(false, ValueWidget.isNullOrEmpty(input4));
		org.junit.Assert.assertEquals(false, ValueWidget.isNullOrEmpty(input5));
		org.junit.Assert.assertEquals(false, ValueWidget.isNullOrEmpty(input6));
		
		org.junit.Assert.assertEquals(false, ValueWidget.isNullOrEmpty(strs1));
		org.junit.Assert.assertEquals(true, ValueWidget.isNullOrEmpty(strs2));
		org.junit.Assert.assertEquals(false, ValueWidget.isNullOrEmpty(strs3));
		org.junit.Assert.assertEquals(true, ValueWidget.isNullOrEmpty(strs4));
	}

那么如何判断一个自定义对象属性是否全为空呢?(这里只考虑对象的属性全为基本类型)?

代码如下:

/***
	 * Determine whether the object's fields are empty
	 * 
	 * @param obj
	 * @param isExcludeZero  :true:数值类型的值为0,则当做为空;----false:数值类型的值为0,则不为空
	 * 
	 * @return
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 */
	public static boolean isNullObject(Object obj, boolean isExcludeZero)
			throws SecurityException, IllegalArgumentException,
			NoSuchFieldException, IllegalAccessException {
		List<Field> fieldList = ReflectHWUtils.getAllFieldList(obj.getClass());
		boolean isNull = true;
		for (int i = 0; i < fieldList.size(); i++) {
			Field f = fieldList.get(i);
			Object propertyValue = null;
			try {
				propertyValue = getObjectValue(obj, f);
			} catch (NoSuchFieldException e) {
				e.printStackTrace();
			}

			if (!ValueWidget.isNullOrEmpty(propertyValue)) {// 字段不为空
				if (propertyValue instanceof Integer) {// 是数字
					if (!((Integer) propertyValue == 0 && isExcludeZero)) {
						isNull = false;
						break;
					}
				} else if (propertyValue instanceof Double) {// 是数字
					if (!((Double) propertyValue == 0 && isExcludeZero)) {
						isNull = false;
						break;
					}
				}else if (propertyValue instanceof Float) {// 是数字
					if (!((Float) propertyValue == 0 && isExcludeZero)) {
						isNull = false;
						break;
					}
				}else if (propertyValue instanceof Short) {// 是数字
					if (!((Short) propertyValue == 0 && isExcludeZero)) {
						isNull = false;
						break;
					}
				}else {
					isNull = false;
					break;
				}
			}
		}
		return isNull;
	}

ValueWidget.isNullOrEmpty 的类com.string.widget.util.ValueWidget.ValueWidget:见 

http://download.csdn.net/detail/hw1287789687/7255307
测试:

package com.test.bean;

import java.sql.Timestamp;

public class Person2 {
	private int id;
	private int age;
	private double weight;
	private String personName;
	private Timestamp birthdate;
	public String identitify;
	protected String address;
	String phone;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPersonName() {
		return personName;
	}
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	public Timestamp getBirthdate() {
		return birthdate;
	}
	public void setBirthdate(Timestamp birthdate) {
		this.birthdate = birthdate;
	}
	public String getIdentitify() {
		return identitify;
	}
	public void setIdentitify(String identitify) {
		this.identitify = identitify;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public double getWeight() {
		return weight;
	}
	public void setWeight(double weight) {
		this.weight = weight;
	}
	
	
}

@Test
	public void test_isNullObject() throws SecurityException,
			IllegalArgumentException, NoSuchFieldException,
			IllegalAccessException {
		Person2 p = new Person2();
		Assert.assertEquals(true, ReflectHWUtils.isNullObject(p, true));
		Assert.assertEquals(false, ReflectHWUtils.isNullObject(p, false));

		p.setAddress("beijing");
		Assert.assertEquals(false, ReflectHWUtils.isNullObject(p, true));
		Assert.assertEquals(false, ReflectHWUtils.isNullObject(p, false));

		p.setAddress(null);
		p.setId(0);
		Assert.assertEquals(true, ReflectHWUtils.isNullObject(p, true));
		Assert.assertEquals(false, ReflectHWUtils.isNullObject(p, false));

	}

参考:http://hw1287789687.iteye.com/blog/1936364

项目代码下载地址:

http://download.csdn.net/detail/hw1287789687/7255307
.

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/131561.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月12日 上午8:46
下一篇 2022年6月12日 上午9:00


相关推荐

  • python基金估值查询_利用python实现基金估值的邮件发送

    python基金估值查询_利用python实现基金估值的邮件发送动机购买过基金的人 肯定都知道 如果想要自己的基金收益高 那么基金跌的时候就要加仓 这样可以拉低自己的持仓成本 对场外基金而言 交易日下午三点前购买 是以当天的基金净值作为今日的成本的 我们可以在蚂蚁财富 蛋卷和天天基金上 看到某只基金当天的估算值 来判断该基金的涨跌情况 就我的经验而言 估算如果是大涨或者大跌 那基本上就是大涨大跌 偏差不很差很多 而如果是小涨或小跌 估值跟最后的结果可能会差很多

    2026年3月18日
    2
  • 计算机不间断电源维修,ups电源工作原理和维修技巧,具体故障现象的分析处理!…

    计算机不间断电源维修,ups电源工作原理和维修技巧,具体故障现象的分析处理!…ups 电源工作原理对于我们在维修上是起到非常重要的作用 一旦遇到应急电源故障问题科技结合以往使用经验和维修技巧进行解决 就像不同类型的 ups 电源就有不同的状况和维修技巧 具体故障现象分析状况请和我一起来看看吧 UPS 不间断电源工作原理 1 在线 UPS 不间断电源在线 UPS 不间断电源的运行方式是市场电力与电力设备之间的隔离 相反 当 UPS 被转换为直流电时 它被分成两种方式给电池充电 而另一种方式是将交

    2026年3月17日
    2
  • python curses_简单的Python的curses库使用教程

    python curses_简单的Python的curses库使用教程curses 库 ncurses 提供了控制字符屏幕的独立于终端的方法 curses 是大多数类似于 UNIX 的系统 包括 Linux 的标准部分 而且它已经移植到 Windows 和其它系统 curses 程序将在纯文本系统上 xterm 和其它窗口化控制台会话中运行 这使这些应用程序具有良好的可移植性 介绍 cursesPython 的标准 curses 提供了 玻璃电传 glas

    2026年3月18日
    2
  • linux中777是什么权限_centos切换到root用户

    linux中777是什么权限_centos切换到root用户基本上就是全部开放读写执行操作权限一个文件有三个权限,分别是读、写和执行,它们对应的数分别是4、2和1。如果某个用户只有读权限没有写和执行权限当然就是4,如果三个如果有读和执行权限就是5(4+1)所以有全部权限就是7了。而一个文件或文件夹面对的用户分三类:所属用户、所属用户的组其他用户以及组外用户。所以777三个数字就是对应这三个用户对象全部都有读、写、执行权限。如果是所属用户有全部权限,组员有读…

    2022年10月9日
    4
  • BREW的COM属性

    BREW的COM属性

    2021年8月2日
    69
  • Redis(2.8版本)配置文件参数中文详解

    Redis(2.8版本)配置文件参数中文详解

    2021年9月2日
    74

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号