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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 什么是exploit

    什么是exploit   exploit字面上的意思是“开拓、开发”,而在激活成功教程圈子里面,公认的概念可能是“漏洞及其利用”。通俗的说,exploit就是利用一切可以利用的工具、采用一切可以采用的方法、找到一切可以找到的漏洞,并且通过对漏洞资料的分析研究,从而达到获取网站用户资料文档、添加自定义用户、甚至侵入网站获得管理员权限控制整个网站的最终目的。对于cracker来说,能够得到密码档或者添加用户就足够了。而对于h

    2025年7月16日
    8
  • VRRP(超详细)

    VRRP(超详细)12VRRP12 1 为什么要有 vrrp 主要为了防止单点故障既有网关冗余 当网关发生故障的时候 能让 PC 快速的切换 12 2VRRP 的概念通过 VRRP 将俩台路由器虚拟构成一台路由器 俩台路由器的浮动地址 即是路由器的虚拟地址 浮动地址也是下行地址的网关 IP 通俗的讲 VRRP 实现了一个组中的路由器 哪个路由器工作 哪个路由器作为备份 实际上 如果一个组中有俩个路由 其可以理解为三个路由

    2025年6月23日
    2
  • oracle 拉链表算法,拉链表设计算法「建议收藏」

    oracle 拉链表算法,拉链表设计算法「建议收藏」在企业中,由于有些流水表每日有几千万条记录,数据仓库保存5年数据的话很容易不堪重负,因此可以使用拉链表的算法来节省存储空间。1.采集当日全量数据存储到ND(当日)表中。2.可从历史表中取出昨日全量数据存储到OD(上日数据)表中。3.用ND-OD为当日新增和变化的数据(即日增量数据)。两个表进行全字段比较,将结果记录到tabel_I表中4.用OD-ND为状态到此结束需要封链的数据。(需要修改…

    2022年10月10日
    2
  • emwin教程_emwin教程

    emwin教程_emwin教程1.位图显示(1)BmpCvt[位图转换器]作用将位图从PC格式转换为C文件,emwin可使用的位图在C文件中定义为GUI_BITMAP结构体。注:如果图片要转化为bmp格式,可以用画图软件,像素大小要合适设置如下:…

    2022年10月14日
    0
  • 软件工程与软件测试_软件工程导论第三版课后答案

    软件工程与软件测试_软件工程导论第三版课后答案1.软件测试基础2.单元测试3.集成测试4. 确认测试5.白盒测试技术6.黑盒测试技术7.调试8.软件可靠性

    2022年8月31日
    8
  • ORACLE触发器(trigger)的使用

    ORACLE触发器(trigger)的使用1、触发器说明触发器是一种在事件发生时隐式地自动执行的PL/SQL块,不能接受参数,不能被显式调用2、触发器语法create[orreplace]triggertrigger_name{before|after|insteadof}trigger_eventon{table_name|view_name}[foreachrow]beginPL/SQL语句…

    2022年7月15日
    18

发表回复

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

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