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);
}
}
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With