Get Entity Field Values as String in Java

The following uses the Apache Commons Lang library that provides the ReflectionToStringBuilder class to assist in the construction of object field values into a single String value.

This is quite useful for the viewing all the objects field values and assignments in an easily readable format.

The below example uses JDK 1.8 and the Apache Commons Lang3 library.

A book object is created and the toString() method is invoked.

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;  
import org.apache.commons.lang3.builder.ToStringStyle;

public class Book {  
    public String title = "";
    public String author = "";
    public String isbn = "";

    public Book(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

    public String toString() {
        ReflectionToStringBuilder
        .setDefaultStyle(ToStringStyle.MULTI_LINE_STYLE);

        return ReflectionToStringBuilder.toString(this);
    }

    public static void main(String[] args) {
        Book book = new Book("Java For Dummies", 
                        "Barry Burd",
            "978-1-118-40780-6");
        System.out.println(book.toString());
    }
}

The book field values are printed to the console and looks something like this.

my.java.project.Book@7aac27[  
  title=Java For Dummies
  author=Barry Burd
  isbn=978-1-118-40780-6
]

This will not work if trying to access private field values and there is a SecurityManager present.

For most though, this is quite helpful for a general inspection of the object or for logging purposes.

References


comments powered by Disqus