1.5. Customizing Generated toString( ) Content
Problem
You need to automate toString( )
while retaining control over the
output, contents, and formatting.
Solution
In addition to the ReflectionToStringBuilder,
Commons Lang provides for customization via the
ToStringBuilder
and
ToStringStyle
class. From the previous recipe, if you
only want the PoliticalCandidate
toString( ) method to print
lastName and firstName, use the
ToStringBuilder class and pass in a
ToStringStyle object. The following example
demonstrates a toString( ) method implementation
that customizes both style and content:
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public String toString( ) {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("lastName", lastName)
.append("firstName", firstName)
.toString( );
}Calling toString( ) on this object will produce
the following output containing only the two properties specified as
parameters to append( ):
com.discursive.jccook.lang.builders.PoliticalCandidate@1cd2e5f[ lastName=Jefferson firstName=Thomas ]
Tip
Unlike the output shown in Recipe 1.4, this output is shown exactly as it appears on your screen.
Discussion
Generating toString( ) content using reflection saves time, but the trade-off is that the code using reflection prints out every member variable of a given class. What do you do when the desired behavior is to print out only a few selected variables from a given class? What ...
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