This is mainly toString
. But if you want this to be done automatically, you can create some general service that can do this. Use reflection to iterate over all the fields, and then print each name and value. The easiest way to print their values โโis to use them toString
, but you can also pass them to this print service recursively in some cases (you, of course, have to find a stop condition).
For example, some PrintUtils classes have:
public static void printFields(Object o) { System.out.print(o.getClass.getSimpleName() + ": "); for (Field field : o.getClass().getDeclaredFields()) { field.setAccessible(true);
You will have to handle exceptions, etc. and it might be better to format the output, of course. In addition, these are only print fields declared in the current class. If you want the fields declared above in the inheritance hierarchy, you have to work a little more. Finally, using reflection is much slower than just regular toString
. If using toString
possible, this is preferable.
source share