1.4. Automating the Generation of toString( ) Content
Problem
You want to automate the creation of toString( )
methods.
Solution
Use the Commons Lang
ReflectionToStringBuilder or
ToStringBuilder and
ToStringBuilder to create toString() methods. The following code is an example of a
toString( ) method, which uses a
reflection builder:
import org.apache.commons.lang.builder.ToStringBuilder;
public void toString( ) {
ReflectionToStringBuilder.toString( this );
}Discussion
Assume that you have an object named
PoliticalCandidate—a bean that represents
some information about a presidential candidate. This bean has a set
of properties: firstName,
lastName, dateOfBirth,
moneyRaised, and homeState.
Example 1-1 shows the
PoliticalCandidate class using a
ReflectionToStringBuilder; the getter and setter
methods have been omitted for brevity.
Example 1-1. The PoliticalCandidate class using ReflectionToStringBuilder
import java.math.*;
import java.util.*;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
public class PoliticalCandidate {
private String lastName;
private String firstName;
private Date dateOfBirth;
private BigDecimal moneyRaised;
private State homeState;
// get/set methods are omitted for brevity...
public void toString( ) {
ReflectionToStringBuilder.toString( this );
}
}The process of keeping the contents of a toString() method synchronized with a changing object model becomes a chore (usually a forgotten one). Commons Lang includes a fairly simple utility designed ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access