How can I reflect 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); } } } 
+6
java arrays reflection
source share
1 answer

You would 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 retrieve the value from the field using Field.get , and then use the java.lang.reflect.Array helper class to access the length and individual elements.

+6
source share

All Articles