Home > database >  How to turn an Object that may be an array or any Collection to a String?
How to turn an Object that may be an array or any Collection to a String?

Time:06-28

I have an Object of which i know that it is either a Collection, something that extends Object[] or any primitive array, and I want to get its String-representation: [e1, e2, ..., en]

  • String.valueOf(object); Doesn't work for arrays and foreign Collections with different toString methods.
  • object.getClass().isArray() ? Arrays.toString((Object[]) object) : String.valueOf(object); Throws a ClassCastException when a primitive array gets passed.
  • "[" Stream.of(object).map(v -> v.toString()).collect(Collectors.joining(", ")) "]"; Interprets the passed object as one element and creates a Stream of that.

I'm looking for a fast solution, preferably one that doesn't rely on libraries. And it shouldn't involve a gigantic if-else/switch block for type checking.

CodePudding user response:

an Object of which I know that it is either a Collection, something that extends Object[] or any primitive array

The overall problem statement sounds very smelly. Even if you didn't develop this code, but inherited from your predecessor, I strongly advise you to replace it with something more viable.

But you can deal with an array of arbitrary type using reflection:

int[] nums = {1, 2, 3};
Object arr = nums;

if (!(arr instanceof Collection<?>)) {
    int len = Array.getLength(arr);
    for (int i = 0; i < len; i  ) {
        System.out.println(Array.get(arr, i));
    }
}

Output:

1
2
3

CodePudding user response:

You can make a class like PrintTools like this:

public class PrintTools {
    
    public static String print(Collection c){
        return c.toString();
    }
    
    public static String print(Object... o){
        return Arrays.deepToString(o);
    }
    
}

So that you will be taken to a proper method depending on argument type.

So your test could be the following:

public class TestPrintTools {

    public static void main(String[] args) {
        A[] a1 = {new A(1), new A(2)};
        int[] a2 = {3, 4};
        List<A> a3 = List.of(new A(5), new A(6));
        System.out.println(PrintTools.print(a1));
        System.out.println(PrintTools.print(a2));
        System.out.println(PrintTools.print(a3));
    }

}

class A{
    int a;

    public A(int a) {
        this.a = a;
    }

    @Override
    public String toString() {
        return "A{"  
                "a="   a  
                '}';
    }
}

with the output:

[A{a=1}, A{a=2}]
[[3, 4]]
[A{a=5}, A{a=6}]
  •  Tags:  
  • java
  • Related