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

Page:    1 2 >

The ApacheSW Jakarta Commons LangS project has many useful classes, including the ToStringBuilder class. This class has a very handy set of static reflectionToString methods that use reflection to read the values of an object's fields and then display their values.

Let's look at an example of the use of the ToStringBuilder class. ToStringBuilder is in the commons-lang jarW file, which currently can be downloaded at http://commons.apache.org/downloads/download_lang.cgi. We can add this jar file to our project and include it in the project's build path.

'testing' project in Eclipse

Let's create a very simple Test class that contains several fields. We won't even supply get methods to retrieve these field values, since ToStringBuilder uses reflection to obtain the field names and their values even though the fields are private.


package test;

import java.util.Date;

public class Test {

	private Date theDate;
	private String theString;
	private boolean theBoolean;
	private String[] stringArray;

	Test() {
		theDate = new Date();
		theString = "My String";
		theBoolean = true;
		stringArray = new String[] { "abc", "def", "ghi" };

(Continued on page 2)

Page:    1 2 >