Java Reflection - Get size of array object

限于喜欢 提交于 2019-12-23 07:48:16

问题


I was wondering if any knows hows to get the size of an array object using reflection?

I have a Vehicles component containing an array object of type Car.

Vehicles.java

public class Vehicles{

    private Car[] cars;

    // Getter and Setters
}

Car.java

public class Car{

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

    // Getter and Setters
}

I was wondering how I would be able to get the size of the cars array within the vehicles component using Java Reflection?

I current have the following:

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

which results in the following error:

java.lang.IllegalArgumentException: Argument is not an array
    at java.lang.reflect.Array.getLength(Native Method)

Any ideas?


回答1:


The method Array.getLength(array) expects an array instance. In you code sample you are calling it on the array type for the field. It won't work as an array field can accept arrays of any lengths!

The correct code is:

Array.getLength(field.get(vehicles))

or simpler

Array.getLength(vehicles.cars);

or simplest

vehicles.cars.length

Take care of a null vehicles.cars value though.




回答2:


I suppose you have to pass the array object itself to Array.getLength() so try

Array.getLength(field.get(vehicles))



回答3:


try

System.out.println(" Length: " + Array.getLength(field.get(vehicles)));


来源:https://stackoverflow.com/questions/15907178/java-reflection-get-size-of-array-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!