Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate over an Array field reflectively?

I have

Class<? extends Object> class1 = obj.getClass();
    Field[] fields = class1.getDeclaredFields();
    for (Field aField : fields) {
      aField.setAccessible(true);
       if (aField.getType().isArray()) {
          for (?? vals : aField) {
            System.out.println(vals);
          }
        }
      }
like image 619
unj2 Avatar asked May 31 '10 06:05

unj2


People also ask

Is it possible to iterate over arrays?

Iterating over an arrayYou can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

What does it mean to iterate over an array?

Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways. Method 1: Using for loop: This is the simplest of all where we just have to use a for loop where a counter variable accesses each element one by one.

Can we use for loop to iterate an object in JavaScript?

Using for...inThe for...in loop below iterates over all of the object's enumerable, non-Symbol properties and logs a string of the property names and their values.


1 Answers

You'd use something like this:

if (aField.getType().isArray()) {
  Object array = aField.get(obj);
  int length = Array.getLength(array);
  for (int i = 0; i < length; i++) {
    System.out.println(Array.get(array, i));
  }
}

In other words, you first fetch the value from the field using Field.get, then use the java.lang.reflect.Array helper class to access the length and the individual elements.

like image 126
Jon Skeet Avatar answered Oct 31 '22 20:10

Jon Skeet