This post will discuss how to print the string representation of an object in Java.

Override the toString() method in Java

 
In the above post, we have discussed how to override the toString() method in Java to print the string representation of an object. This post provides an overview of some of the other alternatives to accomplish this without need to override the toString() method.

1. Using Apache Commons Lang

Apache Commons Lang library provides the ToStringBuilder.reflectionToString() method that uses reflection to generate a string representation for the specified object.

Download Code

Output:

Country@5c29bfd[continent=North America,name=United States,population=4000000]

 
Note that this method might fail under a security manager, since it uses AccessibleObject.setAccessible() to change the visibility of the private fields in the class. Alternatively, you can also use the ReflectionToStringBuilder.toString() method which also uses reflection to access private fields.

Download Code

Output:

Country@5c29bfd[continent=North America,name=United States,population=4000000]

2. Using Project Lombok

With Project Lombok, you can annotate any class with @ToString annotation, to get an implementation of the toString() method consisting of your class name with each field, separated by commas, unless specified otherwise.

The default implementation prints all non-static fields. You can annotate a field with @ToString.Exclude to skip it. Alternatively, you can specify the exact fields to be included in the string representation with @ToString.Include and annotate the class with @ToString(onlyExplicitlyIncluded = true).

3. Using GSON

Alternatively, you can use GSON library to serialize a Java object into JSON string. Gson provide toJson() method to convert Java objects to JSON, which will perform a deep copy using reflection.

Download Code

Output:

{
  "name": "United States",
  "continent": "North America",
  "population": 4000000
}

4. Using Jackson

If you prefer the Jackson library, you can use ObjectMapper#writeValueAsString() method to serialize a Java Object to JSON.

Download  Run Code

Output:

{"name":"United States","continent":"North America","population":4000000}

That’s all about printing the String representation of an object in Java.