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 here with explanation. 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()) {
    field.setAccessible(true);
    String name = field.getName();
    Object value = field.get(abc);
    System.out.printf("%s: %s%n", name, value);
}

Explanation

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.

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 / 5. Vote count:

No votes so far! Be the first to rate this post.

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

Let us improve this post!

Tags:

Leave a Reply

Welcome to CloudiKnow.com 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.