How to print the values of all the fields of an object in java

  • by

Simply copy – paste the below code in your IDE, make class name changes and you’re done. The code is originally taken from “Stack Overflow” and the explanation is not quite much impressive there!

Hence I have written a detailed explanation in this page with animation. We are going to use Java Reflection API to achieve what we are looking for:

ClassABC abc = new ClassABC();
for (Field field : abc.getClass().getDeclaredFields()) {
    String name = field.getName();
    Object value = field.get(abc);
    System.out.printf("%s: %s%n", name, value);


Java Reflection API allows us to browse and use fields and methods of a class instance, that is, of an object of that class. Look at the code example. getClass() method returns the class reference and then you can use getDeclaredFields() method to get all the methods along with methods details like accessible mode, name, and so on.

See the animated view of this explanation here.

So, we have got all the fields of the class of our subjected object and then we are doing ‘for-loop’ over it to print each one of them.

How useful was this post?

Click on a star to rate it!

Average rating 3 / 5. Vote count: 4

We are sorry that this post was not useful for you!

Let us improve this post!


Leave a Reply

Welcome to blog, a platform to share knowledge and solution experience related to public cloud is base design of this site.

You can start the cloud journey right from here!
Please bookmark this page by pressing simply CTRL+D.