Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection - Get size of array object

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?

like image 615
Harvey Sembhi Avatar asked Apr 09 '13 16:04

Harvey Sembhi


People also ask

How do you find the size of an array of objects?

You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.

How to get length of an object in Java?

One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.

Can you use .length on an array of objects?

1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.

What must be true of the length of an array object once it has been instantiated?

An array's length instance variable is constant. – that is, arrays are assigned a constant size when they are instantiated.


1 Answers

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.

like image 161
Guillaume Avatar answered Oct 06 '22 07:10

Guillaume