Here's a simple Java toString
method that I've added to my model objects in a recent project. It uses reflection to dynamically print the fields in your Java class and their values. By using this dynamic toString
method you don't have to custom-code every toString
method in each of your classes.
I can't take credit for any of this though: my simple Java dynamic toString
method just uses the reflectionToString
method of the ToStringBuilder class of the Apache Commons project.
That being said, here's the toString
method in isolation:
// a toString method that can be used in any class. // uses reflection to dynamically print java class field // values one line at a time. // requires the Apache Commons ToStringBuilder class. public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); }
And next, here's how the dynamic toString
method is used in a simple class:
package com.devdaily.tostringtest; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public class User { private int id; private String username; private String password; public static void main(String[] args) { // call our no-args constructor new User(); } public User() { // load up some values id = 1; username = "foo"; password = "bar"; // invoke the toString method with this print statement System.out.println(this); } public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public void setId(int id) { this.id = id; } public int getId() { return id; } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } }
Sample output
If you compile and run this Java class you'll see output as shown below that is generated dynamically:
com.devdaily.tostringtest.User@136228[ id=1 username=foo password=bar ]
For me that's a very cool, very simple way of adding a toString
method to any class. This can be used to debug problems, or however else you want to use it. By using reflection it dynamically prints your output in an easy-to-read format, and unless you need a custom approach, this is about as easy as it gets.