Generate a Custom toString with Apache Commons Lang in NetBeans
A useful toString() implementation makes Java objects easier to inspect during debugging, testing and application support. Rather than displaying an unhelpful class name followed by a memory address, you can produce readable output containing selected fields, labels and nested values.
Apache Commons Lang provides ToStringBuilder, ToStringStyle and ReflectionToStringBuilder for this purpose. In NetBeans IDE, the setup is straightforward with Maven or Gradle, and the result fits neatly into enterprise applications, REST services and ordinary desktop projects.
Add Apache Commons Lang To Your Project
For a Maven project, add the current Apache Commons Lang 3 dependency to pom.xml. NetBeans should download the library automatically after the project reloads. A typical dependency uses the org.apache.commons:commons-lang3 group and an appropriate stable version selected for your Java release.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.17.0</version>
</dependency>
If the project uses Gradle, place the matching library in the dependencies block instead. After saving the build file, use NetBeans code completion to import org.apache.commons.lang3.builder.ToStringBuilder and ToStringStyle. The IDE’s refactoring tools can also help rename fields or update generated methods safely when the model changes.
Build A Readable Custom Representation
Suppose an Australian delivery application contains a Parcel class with an identifier, destination suburb, weight and delivery status. A custom implementation can expose those useful values without printing every internal property.
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class Parcel {
private final String trackingId;
private final String suburb;
private final double weightKg;
private final String status;
public Parcel(String trackingId, String suburb,
double weightKg, String status) {
this.trackingId = trackingId;
this.suburb = suburb;
this.weightKg = weightKg;
this.status = status;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("trackingId", trackingId)
.append("suburb", suburb)
.append("weightKg", weightKg)
.append("status", status)
.toString();
}
}
The output resembles Parcel[trackingId=AU123,suburb=Richmond,weightKg=2.5,status=IN_TRANSIT]. This style is compact enough for NetBeans output windows and application logs, while still making a failed test or an unexpected parcel state easy to recognise in Sydney, Melbourne or Brisbane environments.
Choose The Right ToStringStyle
Commons Lang includes several predefined styles. SHORT_PREFIX_STYLE prints the simple class name, SIMPLE_STYLE omits the class name, and JSON_STYLE creates a JSON-like representation. DEFAULT_STYLE is more verbose and commonly uses a fully qualified class name, which can make logs unnecessarily wide.
The selected style should match the purpose of the output. A short style works well for debugging domain objects, while a multiline style may be better when reading a complex object in the NetBeans debugger. JSON-like output can look convenient, but it is not automatically a valid API response or a substitute for a JSON library such as Jackson.
For a collection or nested object, Commons Lang can append the value directly:
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("customer", customer)
.append("items", items)
.append("total", total)
.toString();
Use this carefully when nested objects have their own verbose toString() methods, since a small log entry can expand rapidly.
Use Reflection With Care
ReflectionToStringBuilder can include fields automatically, which is convenient for prototypes and classes with many simple properties:
@Override
public String toString() {
return ReflectionToStringBuilder.toString(
this,
ToStringStyle.SHORT_PREFIX_STYLE
);
}
Automatic reflection reduces maintenance when fields are added, but it also removes control over what becomes visible. Passwords, access tokens, payment details, session identifiers and private customer information should never appear in ordinary logs. This matters for Australian businesses handling customer records under the Privacy Act and for systems that integrate with local banks, retailers or logistics providers.
A manually selected builder is usually the safer production choice. If reflection is necessary, exclude sensitive fields with an explicit configuration or use a dedicated logging representation. For performance-sensitive applications, check the effect of repeated object formatting with VisualVM profiling, especially when large collections or entity graphs are involved.
Test And Maintain The Generated Output
A toString() method should be tested like any other useful diagnostic feature. Create a unit test that constructs a representative object and checks for important labels and values. Avoid asserting the entire string unless its exact formatting is part of the application contract, because changing from short-prefix to multiline style would otherwise break harmless tests.
NetBeans makes it easy to place a breakpoint in toString(), inspect fields and compare output in the debugger. This is particularly helpful for Java EE objects, where a log entry may contain a session bean proxy, an entity identifier or a message payload. A stateful session bean may retain conversational state, so logging carefully chosen fields can reveal lifecycle problems without exposing the complete object graph.
Practical Recommendations For Safer Object Output
Keep the representation stable enough for developers to recognise, but avoid treating it as a serialisation format. The method is primarily for diagnostics, and its output may appear in test reports, server logs, support tickets or screenshots shared between teams in Perth, Adelaide and Canberra.
- Prefer
ToStringBuilderwhen you need precise control over included fields. - Select
SHORT_PREFIX_STYLEfor compact logs andMULTI_LINE_STYLEfor detailed debugging. - Exclude passwords, tokens, personal data and confidential business values.
- Add unit tests that verify important fields without overcommitting to punctuation.
- Avoid reflection for sensitive domain objects unless exclusions are explicit.
- Check nested collections and relationships to prevent unexpectedly large log messages.
- Review the output after renaming fields, changing packages or upgrading Commons Lang.