Java Reflection - get the size of an array object

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

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

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 can I get the size of an array of cars in a component for vehicles using Java Reflection?

I current has 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 leads to the following error:

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

Any ideas?

+7
source share
3 answers

The Array.getLength(array) method Array.getLength(array) instance. In your code example, you call it by the type of the array for the field. It will not work, as the array field can accept arrays of any length!

The correct code is:

 Array.getLength(field.get(vehicles)) 

or simpler

 Array.getLength(vehicles.cars); 

or the simplest

 vehicles.cars.length 

Take care of the zero value of vehicles.cars .

+11
source

Suppose you need to pass an array object to Array.getLength() , so try

 Array.getLength(field.get(vehicles)) 
+4
source

to try

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

All Articles