Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if an object is primitive type or an array of primitive type in Java?

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?

like image 576
le-doude Avatar asked Oct 24 '25 03:10

le-doude


1 Answers

  • To test if object is an array just getClass() and see if it isArray().
  • To get type of elements array is declared to hold use getComponentType() on Class instance.
  • To test if some type is primitive you can use isPrimitive().
  • If you want to check if type represents String just use 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;}
like image 172
Pshemo Avatar answered Oct 27 '25 00:10

Pshemo