Java Reflection - 获取数组对象的大小

Har*_*bhi 8 java arrays reflection size illegalargumentexception

我想知道是否知道如何使用反射获得数组对象的大小?

我有一个车辆组件包含类型为Car的数组对象.

Vehicles.java

public class Vehicles{

    private Car[] cars;

    // Getter and Setters
}
Run Code Online (Sandbox Code Playgroud)

Car.java

public class Car{

    private String type;
    private String make;
    private String model;

    // Getter and Setters
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用Java Reflection 在车辆组件中获得汽车阵列的大小?

我目前有以下内容:

final Field[] fields = vehicles.getClass().getDeclaredFields();

if(fields.length != 0){
    for(Field field : fields){
        if(field.getType().isArray()){
            System.out.println("Array of: " + field.getType());
            System.out.println(" Length: " + Array.getLength(field.getType()));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

java.lang.IllegalArgumentException: Argument is not an array
    at java.lang.reflect.Array.getLength(Native Method)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Gui*_*ume 12

该方法Array.getLength(array)需要一个数组实例.在您的代码示例中,您将在字段的数组类型上调用它.它不会工作,因为数组字段可以接受任何长度的数组!

正确的代码是:

Array.getLength(field.get(vehicles))
Run Code Online (Sandbox Code Playgroud)

或者更简单

Array.getLength(vehicles.cars);
Run Code Online (Sandbox Code Playgroud)

或者最简单

vehicles.cars.length
Run Code Online (Sandbox Code Playgroud)

但要注意空vehicles.cars值.

  • 好吧,你不妨说cars.length :-) (2认同)