0

I have the following class:

public class GeneralClass
{
    public int x;
    public int[] arr = new int[3];
}

And the following logic:

public void loadClass(Class cls) {          
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {            
            if (field.getType().isArray()) {
                // How can I print the array length ?
            }
    }
}

How can I know what is the size (length) of the array ?

David Conrad
  • 15,432
  • 2
  • 42
  • 54
user3668129
  • 4,318
  • 6
  • 45
  • 87

5 Answers5

8

You can use Array.getLength, however you need to provide a concrete instance so that's why I use cls.newInstance() (it's assuming there is a no-arg constructor)

public static void loadClass(Class<?> cls) throws IllegalArgumentException, IllegalAccessException, InstantiationException {          
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {      
                if (field.getType().isArray()) {
                    int length = Array.getLength(field.get(cls.newInstance()));
                    System.out.println(length);
                }
        }
    }

Note that if the field was static you could get it at a class level, so int length = Array.getLength(field.get(null)); would work.

user2336315
  • 15,697
  • 10
  • 46
  • 64
2

The array field arr belongs to an instance of the class, hence its length cannot be determined by the Field object obtained via reflection as this is essentially class level metadata.

Invisible Arrow
  • 4,625
  • 2
  • 23
  • 31
  • But we declared the array size in the class ? (it is not enogth) ? – user3668129 Nov 20 '14 at 19:34
  • @user3668129 Read the answer, especially this part: "[...] belongs to an _instance_ of the class". On an instance level you could read the size of the array (with the reflectional approach), on the class level you cannot. – Seelenvirtuose Nov 20 '14 at 19:38
0

Simple

System.out.println(field.length);
0

the way to find the length of an array is fields.length

Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
Jamie Paolino
  • 597
  • 4
  • 6
-1

Array length is fairly easy. It is

arrayName.length 

So you can say :

System.out.print(   "length  is " +  arr.length  );

Where is array's length property defined?

Community
  • 1
  • 1
Caffeinated
  • 11,982
  • 40
  • 122
  • 216