public class MyClass { ClassABC abc = new ClassABC(); } I just have a .class file of ClassABC. I want to print all the public, private, protected and default field values of "abc" object. How can I do this using Reflection?
You can get all fields by Class#getDeclaredFields(). Each returns a Field object of which you in turn can use the get() method to obtain the value. To get the values for non-public fields, you only need to set Field#setAccessible() to true.
So, in a nut:
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("Field name: %s, Field value: %s%n", name, value); } If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With