The essence of the question is this. There is a certain class:

public class TestClass { private static final int i = 9; private int[] array = {1, 4, 9}; private Object[] array2 = {new Date(), new Date()}; } 

Next, do the following:

 Field[] fields = TestClass.class.getDeclaredFields(); for (Field field : fields) { System.out.println(field.get(new TestClass())); } 

Here we get an array in which the fields of our class lie. Next, we need to display the values ​​of these fields. But if we have a field - an array, then we need to display all the elements of this array, and not the link. How to do it?

    2 answers 2

    Arrays.deepToString able to output arrays of any dimension and, if there are no strict requirements for the format, you can write shortly and without reflection:

     Object value = field.get(new TestClass()); System.out.println(Arrays.deepToString(new Object[]{value})); 

    This code will support arrays of any dimension ( String[][] , int[][][] ). The output will be:

     [9] [[1, 4, 9]] [[Fri Mar 30 13:06:50 GMT 2018, Fri Mar 30 13:06:50 GMT 2018]] 

    If necessary, extra square brackets can be cut:

     Object value = field.get(new TestClass()); String valueText = Arrays.deepToString(new Object[]{value}); valueText = valueText.substring(1, valueText.length()-1); System.out.println(valueText); 

    This method will not work if you need your own format for output, or if you need not to output, but somehow otherwise handle the resulting array. In this case, you will need to use reflection ( see the answer @Sergey Gornostaev ) and, if you need to support multi-dimensional arrays, recursion.

    A similar discussion in English with options for processing various arrays and a deceptive heading:

    • thank you so much - Valentyn Anzhurov
    • @ValentineAnzhurov Please! - default locale
     import java.lang.reflect.Field; import java.lang.reflect.Array; import java.util.Date; public class Main { private static final int i = 9; private int[] array = {1, 4, 9}; private Object[] array2 = {new Date(), new Date()}; public static void main(String[] args) throws Exception { Main obj = new Main(); for (Field field : Main.class.getDeclaredFields()) { if (field.getType().isArray()) { Object array = field.get(obj); int length = Array.getLength(array); System.out.print("["); for (int i = 0; i < length; i++) { if (i != 0) System.out.print(", "); System.out.print(Array.get(array, i)); } System.out.println("]"); } else { System.out.println(field.get(obj)); } } } }