I am trying to filter methods which has primitive arrays as their arguments. One of the method signature is as follows:
public void myMeth(int[]);
public void myMeth(double[]);
Executing the following program,
public class MyClass {
public static void main(String args[]) {
System.out.println(int[].class);
System.out.println(int[].class.isPrimitive());
System.out.println(Integer[].class);
System.out.println(int.class);
System.out.println(int.class.isPrimitive());
}
}
I get the following output:
class [I
false
class [Ljava.lang.Integer;
int
true
Now my questions are:
int
is primitive type, why is not int[]
primitive?
- Since
int
is primitive type, why is notint[]
primitive?
Any array is an object in Java because it can be created with new
operator as follows:
int[] a = new int[5];
Also, array is a sub-class of Object, therefore you can call all Object class' methods on the array object.
int[] a = new int[5];
int x = 10;
System.out.println(a.toString());
System.out.println(x.toString()); // compile-time error
From the Java Specification: Section #4.3.1
An object is a class instance or an array.
So, the condition (type.isArray() && type.isPrimitive())
is always false
because array is not a primitive type.
- How to know if a type is a primitive array?
You need to make use of the getComponentType()
method. From Javadocs
Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.
So, the code snippet would be:
public static boolean isPrimitiveArray(Class<?> type) {
Class<?> componentType = type;
while ((componentType = componentType.getComponentType()) != null) {
if (componentType.isPrimitive()) {
return true;
}
}
return false;
}
System.out.println(isPrimitiveArray(int[].class)); // true
System.out.println(isPrimitiveArray(int[][].class)); // true
System.out.println(isPrimitiveArray(int[][][].class)); // true
System.out.println(isPrimitiveArray(Integer.class)); // false
System.out.println(isPrimitiveArray(Integer[].class)); // false
System.out.println(isPrimitiveArray(int.class)); // false
or if we want to check dimensions also..
public static boolean isPrimitiveArray(Class<?> type, int dimensions) {
Class<?> componentType = type;
int count = 0;
while ((componentType = componentType.getComponentType()) != null) {
count++;
if (componentType.isPrimitive() && dimensions == count) {
return true;
}
}
return false;
}
System.out.println(isPrimitiveArray(int[].class,1)); // true
System.out.println(isPrimitiveArray(int[][].class,2)); // true
System.out.println(isPrimitiveArray(int[][][].class,2)); // false