[英]Given that an Object is an Array of any type how do you test that it is empty in Java?
请帮我完成我的isEmpty方法:
public static boolean isEmpty(Object test){
if (test==null){
return true;
}
if (test.getClass().isArray()){
//???
}
if (test instanceof String){
String s=(String)test;
return s=="";
}
if (test instanceof Collection){
Collection c=(Collection)test;
return c.size()==0;
}
return false;
}
我将int设置为什么代码来确定如果我正在处理一个数组,如果它的长度为零,它将返回true? 无论类型是int [],Object [],我希望它能工作。 (大家都知道,我可以告诉你,如果你把一个int []放到一个Object []变量中,它会抛出异常。)
您可以使用java.reflect.Array
的helper方法getLength(Object)
:
public static boolean isEmpty(Object test){
if (test==null){
return true;
}
if (test.getClass().isArray()){
return 0 == Array.getLength(test);
}
if (test instanceof String){
String s=(String)test;
return s.isEmpty(); // Change this!!
}
if (test instanceof Collection){
Collection c=(Collection)test;
return c.isEmpty();
}
return false;
}
请注意,您无法使用
boolean empty = (someString == "");
因为那不安全 要比较字符串,请使用String.equals(String)
,或者在这种情况下,只检查长度是否为零。
您可以使用java.lang.reflect.Array#getLength
。
另请注意,您对String
的测试将无法按预期工作。
构建一些空检查的第三个选项是Apache的ArrayUtils
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.