[英]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.