請對以下類別看,我需要檢查,如果存在變量的有效值。所有工作正常,如果存在變量,而不是null
一個合適的值,當談到null,則行爲是不是我所期望的(雖然它可能是有道理的,如果Integer a = null;
時爲a instanceof Integer
檢查,Java的強制類型轉換,對象類型和超載問題
可有人指導我如何從下面的類實現正確的結果?
package com.mazhar.hassan;
public class ValueChecker {
public static boolean empty(Integer value) {
System.out.println("Integer");
return (value != null && value.intValue() > 0);
}
public static boolean empty(Long value) {
System.out.println("Long");
return (value != null && value.longValue() > 0);
}
public static boolean empty(String value) {
System.out.println("String");
return (value != null && value.length() > 0);
}
public static boolean empty(Object value) {
System.out.println("Object");
return (value != null);
}
public static void checkAll(Object... args) {
for(Object o: args) {
if (o instanceof Integer) {
empty((Integer)o);
}
else if (o instanceof Long) {
empty((Long)o);
}
else if (o instanceof String) {
empty((String)o);
}
else {
empty(o);
}
}
}
public static void main (String[] args) {
Integer a = null;
Long b = null;
String x = null;
Object y = null;
if (a instanceof Integer) {
System.out.println("a is Integer");
} else {
System.out.println("a is not Integer");
}
System.out.println("/---------------------------------------------------/");
checkAll(a,b,x,y);
System.out.println("/---------------------------------------------------/");
empty(a);
empty(b);
empty(x);
empty(y);
}
}
爲什麼我需要確切類型檢查,我thave扔誤差修改,如「不是有效的整數」,「無有效龍」等
以上級的輸出如下。
/-----------------------(Output 1)----------------------------/
a is not Integer
/-----------------------(Output 2)----------------------------/
Object
Object
Object
Object
/------------------------(Output 3)---------------------------/
Integer
Long
String
Object
輸出1:a不是整數(通過的instanceof選中)不能識別它,但傳遞給重載函數時轉到正確的功能(輸出3)
輸出2:如何實現checkAll
與多/動態PARAM checkAll(varInt,varLong,varString,varObject)
我認爲你應該提出一個通用的空指針錯誤,類似「字段不能爲空」,如果有任何數據,那麼驗證具體的格式(在這種情況下,你甚至不需要的實例)。這也將避免膠水代碼(如果xxx!= null,則複製並粘貼)。讓我知道這是否符合您的需求。 –