I'd like to create a method that checks every Object's value is empty.If the input object is null
then return true;
.If input is type of array, check it's length. Below is my method to implement this logic
public static boolean isEmpty(Object input) {
if (input == null) {
return true;
}
if (input instanceof Collection) {
if (((Collection<?>) input).size() == 0) {
return true;
}
}
if (input instanceof String) {
if (((String) input).trim().length() == 0) {
return true;
}
}
if (input instanceof Object[]) {
if (((Object[]) input).length == 0) {
return true;
}
}
return false;
}
But the problem is while I testing as like this
int[] a = {};
float[] b = {};
Integer[] c = {};
Float[] d = {};
System.out.println(Validator.isEmpty(a));
System.out.println(Validator.isEmpty(b));
System.out.println(Validator.isEmpty(c));
System.out.println(Validator.isEmpty(d));
I have no idea why a
and b
are false
. Can somebody explain me ?
1 Answer 1
float[]
is not instanceof Object[]
. If you want to check for all kinds of arrays, you probably want to get the class from the object and check its isArray
method. Then you can use Array.getLength
to get its length (since, bizarrely, you can't use Class#getField
to get the length
field):
import java.lang.reflect.*;
class Validator {
public static void main(String args[]) throws Exception {
int[] a = {};
float[] b = {};
Integer[] c = {};
Float[] d = {};
System.out.println(Validator.isEmpty(a)); // true
System.out.println(Validator.isEmpty(b)); // true
System.out.println(Validator.isEmpty(c)); // true
System.out.println(Validator.isEmpty(d)); // true
System.out.println(Validator.isEmpty(new float[3])); // false (just double-checking)
}
public static boolean isEmpty(Object input) {
if (input == null) {
return true;
}
if (input instanceof String) {
if (((String) input).trim().length() == 0) {
return true;
}
}
if (input.getClass().isArray()) {
return Array.getLength(input) == 0;
}
return false;
}
}
-
Thanks alot for code example. I'm still trouble about
how to change my method?
before this.Cataclysm– Cataclysm2016年11月06日 14:08:48 +00:00Commented Nov 6, 2016 at 14:08 -
@Cataclysm: Yeah, it turned out to be more of a pain than I was expecting... I wasn't expecting
Class#getField
to refuse to give me thelength
field of an array (although it's in the documentation, as it turns out).T.J. Crowder– T.J. Crowder2016年11月06日 14:09:49 +00:00Commented Nov 6, 2016 at 14:09
new float[0] instanceof Object[]
?isEmpty
methods which take different type arguments?Incompatible conditional operand types float[] and Object[]
isEmpty
method for all primitive array typesCharSequence
instead of justString
. This will catch not only String but also StringBuilder and many other string-like objects.