判断一个对象是否为空
程序员文章站
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;
}