如何检查Java中的类型是否为原始数组?

How to check if a type is a primtive array in Java?

我正在尝试过滤以原始数组作为参数的方法。 其中一个方法签名如下:

public void myMeth(int[]);
public void myMeth(double[]);

正在执行以下程序,

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());
    }
}

我得到以下输出:

class [I
false
class [Ljava.lang.Integer;
int
true

现在我的问题是:

  1. 既然int是原始类型,为什么int[]不是原始类型?
  2. 如何知道一个类型是否为原始数组?
  1. Since int is primitive type, why is not int[] primitive?

任何数组都是 Java 中的对象,因为它可以使用 new 运算符创建,如下所示:

int[] a = new int[5];

此外,数组是 Object 的子class,因此您可以调用数组对象上的所有 Object class' 方法。

  int[] a = new int[5];
  int x = 10;
  System.out.println(a.toString());
  System.out.println(x.toString()); // compile-time error

来自Java Specification: Section #4.3.1

An object is a class instance or an array.

因此,条件 (type.isArray() && type.isPrimitive()) 总是 false 因为数组不是原始类型。


  1. How to know if a type is a primitive array?

您需要使用getComponentType()方法。来自 Javadocs

Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.

因此,代码片段将是:

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

或者如果我们还想检查尺寸..

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