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


相关推荐

  • 深入浅出Nginx

    深入浅出Nginx

    2022年2月15日
    76
  • springboot Jpa多数据源(不同库)配置

    springboot Jpa多数据源(不同库)配置一、前言springboot版本不同对多数据源配置代码有一定影响,部分方法和配置略有不同。本文采用的springboot版本为2.3.12,数据源为mysql和postgresql二、配置实战2.1基础pom<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</ar

    2022年10月20日
    3
  • antd table编辑_vue修改组件样式

    antd table编辑_vue修改组件样式.ant-table-wrapper{width:98%;height:100%;position:relative;top:30px;}.ant-table{background-color:rgb(9,100,100);color:white;}//表头样式.ant-table-thead>tr>th{background-color:rgb(3,50,50);color:white;}//修改

    2025年11月19日
    4
  • Python 编译器_如何在pe系统里安装软件

    Python 编译器_如何在pe系统里安装软件好久都没更新博客了,最近是真的很忙,每天抽出1小时写博客,有的时候更本没时间,今天写一个解析PE的一个软件,过程和内容很干,干货干货之前有很多人加我要资料和软件,我从来没说过要钱什么的,只要给个关注和点赞,就可以了,需要什么资料,只要我可以给,我会不要一分钱免费给你们资料,欢迎大家来评论博主?点个赞留个关注吧!!资料(百度网盘)提取码:i4ptPE解析软件和源代码包文件提取码:07bhPE解析器软件安装包提取码:r9og激活成功教程版打包软件–打包为安装包先看视频,双击打开

    2022年10月16日
    2
  • 打造自己的HelloDrone 无人机APP过程《0》

    打造自己的HelloDrone 无人机APP过程《0》目录文章目录目录摘要1.项目设置1.设置一个基本的AndroidStudio项目2.添加客户端库3.实现TowerListener的监听事件4.初始化ControlTower并绑定activity的生命周期5.实现无人机监听事件6.无人机实例化并在tower上注册摘要本节主要记录开发自己的HelloDrone无人机的过程,本节是第一节欢迎批评指正!参考资料:博客参考dronekit-android源码Tower源码usb-serial-for-android库1.项目设置1.设

    2022年8月15日
    7
  • IP地址、子网掩码、默认网关和DNS服务器之间的联系与区别

    IP地址、子网掩码、默认网关和DNS服务器之间的联系与区别转自:[https://www.cnblogs.com/JuneWang/p/3917697.html]IP地址,子网掩码、默认网关,DNS服务器是什么意思?(一)问题解析问:IP地址,子网掩码,默认网关,DNS服务器,有什么区别呀?我知道没有IP地址就不能上网,我也知道没设DNS就不能上外网,可它们都有什么功能,有什么区别呢?还有真奇怪,我的计算机没设DNS,竟然能上QQ,却不能…

    2022年4月30日
    78

发表回复

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

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