欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断一个对象是否为空

程序员文章站 2024-02-20 20:45:40
...

Java程序中判断一个对象是否为空的一个小总结

public static <T> T requireNonNull(T obj, String message) {
		if (obj == null)
		{
			 throw new NullPointerException(message);
		}
		else if(obj instanceof Collection)
        {
        	Collection<?> newObj = (Collection<?>)obj;
        	if(newObj.isEmpty())
        	{
        		throw new NullPointerException(message);
        	}else{
        		if(newObj.size()==1)
        		{
        			Iterator iterator = newObj.iterator();
        			while(iterator.hasNext())
        			{
        				Object value = iterator.next();
        				if(value == null)
        				{
        					throw new NullPointerException(message);
        				}
        			}
        		}
        	}
        }else if(obj instanceof Map)
        {
        	Map<?, ?> newObj = (Map<?, ?>)obj;
        	if(newObj.isEmpty())
        	{
        		throw new NullPointerException(message);
        	}
        }
		return 	obj;
    }