jeudi 5 août 2021

How to print array of any type stored as Object variable?

The code below would print array as a cryptic strings


NOTE: a similar question with Arrays.toString(arr) answer doesn't help, as in this case the type of variable passed to arr parameter will be Object and Arrays.toString(Object arr) method doesn't exist.

I tried to use something along Arrays.toString((?[])v) since at compilation time I will not know exact type of array, but this is not valid Java syntax.


import java.io.*;
import java.lang.reflect.*;
import java.util.ArrayList;

public class Play {
  public ArrayList<Integer> list = new ArrayList<>();
  public int[] iarray            = {1, 2, 3};
  public boolean[] barray        = {true, false};

  public static void main(String[] args) throws IOException, IllegalAccessException {
    Play o = new Play();
    // Is it possible to initialize it in constructor as {1, 2}?
    o.list.add(1);
    o.list.add(2);

    Field[] fields = o.getClass().getDeclaredFields();
    for (Field field : fields) {
      Object v = field.get(o);
      // Object s = v.getClass().getName().startsWith("[") ? Arrays.toString((?[])v) : v;
      System.out.println(v);
    }
  }
}

Output

[1, 2]
[I@3498ed
[Z@1a407d53

Is there a way to print below result without a switch/case for every int/bool/double/string type?

[1, 2]
[1, 2, 3]
[true, false]




Aucun commentaire:

Enregistrer un commentaire