Implementing toString()
method sometimes can become a time-consuming process. If you have a class with a few fields, it might be alright. However, when you deal with a lot of 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 produced 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.14.0</version>
</dependency>
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024