- 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 array of primitive type or array of strings 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 primitive type values because it expect Object obj
which means that it enforces autoboxing of any primitive type value to its wrapper class. For instance if wa call it like isBaseTypeOrArray(1)
primitive int
1 will be wrapped to Integer
1.
To accept arguments of pure primitive type (like int
and not Integer
) we need overloaded versions of that method which would accept primitive types like boolean 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.
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;}