I have an object of type Object, and I want to return a String representation of it using the toString() method, except if it is an array, I want to return Arrays.toString() of the object (I don’t need a deepToString).
I thought about using this :
public static String getValueAsString(Object value){
if(value != null && value.getClass().isArray()){
if(value instanceof Object[])
return Arrays.toString((Object[])value);
else if(value instanceof int[])
return Arrays.toString((int[])value);
else ...
}else
return String.valueOf(value);
}
The problem is that I can detect it is an array, but I have to handle all the different primitive array …
Is there a cleaner way to achieve this ? using core methods or reflection ?
You can use the generic
Arrayclass to iterate any array like this:Example:
Outputs: