Reputation: 14711
I have a logger class and here is one of its methods:
public static void i(String tag, Object message) {
if (message != null) {
i(tag, message.toString());
} else {
i(tag, ERROR_PARAMETER_IS_NULL_OR_EMPTY);
}
}
this message!=null
check is not sufficient for List
, Map
, Set
or array
, in the case when they are not null but they are empty. So how do I test if the passed object is something that has a size
or a length
so that I show the ERROR_PARAMETER_IS_NULL_OR_EMPTY
message?
Upvotes: 1
Views: 106
Reputation: 1807
You can use Class.isArray()
:
public static boolean isArray(Object obj)
{
return obj!=null && obj.getClass().isArray();
}
Also works for arrays with primitive types.
And you can use Class.isAssignableFrom(Class<?> cls)
to check whether object is an instance of Collection
:
public static boolean hasSize(Object obj)
{
return obj!=null && Collection.class.isAssignableFrom(obj.getClass());
}
Upvotes: 4
Reputation: 65803
You could avoid the test completely by overloading the method and providing an Iterable
version.
// Shouldn't really use raw types here.
public static void i(String tag, Iterable messages) {
if (messages != null) {
/*
Probably need a bit more than this
as String.join takes an `Iterable<? extends CharSequence>
but that is not an insurmountable problem.
*/
i(tag, "["+String.join(",", messages)+"]");
} else {
i(tag, ERROR_PARAMETER_IS_NULL_OR_EMPTY);
}
}
public static void i(String tag, Object message) {
if (message != null) {
i(tag, message.toString());
} else {
i(tag, ERROR_PARAMETER_IS_NULL_OR_EMPTY);
}
}
Upvotes: 2
Reputation: 35417
To answer your broader question:
static boolean isEmptyArray(Object o) {
if (o == null || !o.getClass().isArray()) {
return false;
}
if (o instanceof int[]) {
return ((int[])o).length == 0;
} else if (o instanceof long[]) {
return ((long[])o).length == 0;
} else if (o instanceof double[]) {
return ((double[])o).length == 0;
} else if (o instanceof byte[]) {
return ((byte[])o).length == 0;
} else if (o instanceof char[]) {
return ((char[])o).length == 0;
} else if (o instanceof boolean[]) {
return ((boolean[])o).length == 0;
} else if (o instanceof float[]) {
return ((float[])o).length == 0;
} else if (o instanceof short[]) {
return ((short[])o).length == 0;
} else { // it is an array, so it can only be an object array now.
return ((Object[])o).length == 0;
}
}
static boolean isEmptyCollection(Object o) {
return (o instanceof Collection) && ((Collection)o).isEmpty();
}
Upvotes: 1