How to print the values of all the fields of an object in Java
August 17, 2011 Comments
I was just doing some Java coding and I needed to check the values of a bunch of fields of an object (mostly numbers). Normally I’d just call and print each get() method if I just need to check a few fields, but the class I’m dealing with has over 30 fields and I need to check them all and there’s no way I’m doing over 30 print statements for each get() method!
A quick Google search led me to this StackOverflow post which has exactly what I was looking for:
ClassABC abc = new ClassABC(); for (Field field : abc.getClass().getDeclaredFields()) { field.setAccessible(true); String name = field.getName(); Object value = field.get(abc); System.out.printf("%s: %s%n", name, value); }
Tags: howto, tech, software development, java