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;
}