One possible way to do this for any object without using an external library is to use a generic reflection. In the following snippet, we simply access each field (including private fields) and print their name and value:
public static <T> String printObject(T t) {
StringBuilder sb = new StringBuilder();
for (Field field : t.getClass().getDeclaredFields()) {
field.setAccessible(true);
try {
sb.append(field.getName()).append(": ").append(field.get(t)).append('\n');
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
This method can be placed in the utility class for easy access.
If any of the fields of the object does not override Object#toString, it simply prints the type of the object and its hash code.
Example:
public class Test {
private int x = 5;
private int y = 10;
private List<List<Integer>> list = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));
}
>> printObject(new Test());
>>
>> x: 5
>> y: 10
>> list: [[1, 2, 3], [4, 5, 6]]
source
share