Implementing toString()
method sometimes can become a time-consuming process. If you have a class with a few fields it might be alright, but when you deal with a many fields it will surely take some time to update this method every time a new field comes and goes.
Here comes the ReflectionToStringBuilder
class that can help you to automate the process of implementing the toString()
method. This class provides a static toString()
method that takes at least a single parameter that refer to an object instance from where the string will be generated.
We can also format the result of the generated string. In the example below we create the to string method with a ToStringStyle.MULTI_LINE_STYLE
and we can also output transients and static fields if we want, which by default omitted.
package org.kodejava.commons.lang;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class ReflectionToStringDemo {
public static final String KEY = "APP-KEY";
private Integer id;
private String name;
private String description;
private transient String secretKey;
public ReflectionToStringDemo(Integer id, String name, String description,
String secretKey) {
this.id = id;
this.name = name;
this.description = description;
this.secretKey = secretKey;
}
public static void main(String[] args) {
ReflectionToStringDemo demo = new ReflectionToStringDemo(1, "MANUTD",
"Manchester United", "secret**");
System.out.println("Demo = " + demo);
}
@Override
public String toString() {
// Generate toString including transient and static fields.
return ReflectionToStringBuilder.toString(this,
ToStringStyle.MULTI_LINE_STYLE, true, true);
}
}
The output produce by the code snippet above is:
Demo = org.kodejava.example.commons.lang.ReflectionToStringDemo@452b3a41[
id=1
name=MANUTD
description=Manchester United
KEY=APP-KEY
secretKey=secret**
]
Maven Dependencies
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023