What's a quick way to output the fields of an object?
Author: Deron Eriksson
Description: This Java tutorial demonstrates using the ToStringBuilder class to output an object's fields.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.1
(Continued from page 1) The ToStringBuilderTest class contains our main method and a couple private fields. At the beginning of main, a ToStringBuilderTest object is instantiated. Then, ToStringBuilder.reflectionToString is called with the ToStringBuilderTest object as a parameter. The returned results of this method call are displayed to standard output. Following this, a Test object is created, and ToStringBuilder.reflectionToString is called with two parameters. The first parameter is the Test object, and the second parameter specifies that we'd like to display the returned results on multiple lines. The results are displayed to standard output. ToStringBuilderTest.javapackage test; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public class ToStringBuilderTest { private int testNum = 123; private String testString = "hamburger"; public static void main(String[] args) { ToStringBuilderTest tsbt = new ToStringBuilderTest(); String result1 = ToStringBuilder.reflectionToString(tsbt); System.out.println(result1); Test test = new Test(); String result2 = ToStringBuilder.reflectionToString(test, ToStringStyle.MULTI_LINE_STYLE); System.out.println(result2); } } If we run ToStringBuilderTest, we see these results: As you can see, the first ToStringBuilder.reflectionToString call displays the fields of ToStringBuilderTest on a single line, and the second ToStringBuilder.reflectionToString call displays the fields of the Test object on multiple lines. Related Tutorials:
|