Here the function signature I would like to implement.
public boolean isBaseTypeOrArray(Object obj){~}
I want to return true only if obj is of one of the following types.
boolean or boolean[]
byte or byte[]
short or short[]
int or int[]
long or long[]
float or float[]
double or double[]
char or char[]
java.lang.String or String[]
For a lone value checking if it is instance of one of the wrapper classes (Integer, Float, ...) or String should work because of auto boxing but I do not know how to check for the array case. Any ideas?
getClass() and see if it isArray().getComponentType() on Class instance.isPrimitive().equals(String.class).So to test if Object represents String, or an array of Strings, or array of primitive type you can use
public static boolean isBaseTypeOrArray(Object obj) {
Class<?> c = obj.getClass();
return c.equals(String.class)
|| c.equals(String[].class)
|| c.isArray() && c.getComponentType().isPrimitive();
}
Problem with above method is that it can't accept purely primitive type values because its parameter is declared as Object obj. This means that even if we pass primitive type value like isBaseTypeOrArray(1), the int value 1 will be autoboxed to reference type Integer also representing 1.
To accept arguments of purely primitive types (like int instead of generated Integer) we need to overload this isBaseTypeOrArray(Object obj) method with versions accepting primitive types - like isBaseTypeOrArray(int obj). Such methods can immediately return true as result, because fact that they ware invoked means that primitive type value was passed as argument (remember that isBaseTypeOrArray(Object) would handle all non-primitive types).
So to handle all primitive types we need to add below methods:
public static boolean isBaseTypeOrArray(boolean obj) {return true;}
public static boolean isBaseTypeOrArray(byte obj) {return true;}
public static boolean isBaseTypeOrArray(short obj) {return true;}
public static boolean isBaseTypeOrArray(char obj) {return true;}
public static boolean isBaseTypeOrArray(int obj) {return true;}
public static boolean isBaseTypeOrArray(long obj) {return true;}
public static boolean isBaseTypeOrArray(float obj) {return true;}
public static boolean isBaseTypeOrArray(double obj) {return true;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With