Guava MoreObjects.ToStringHelper() method in Java
This post will discuss how to create toString() method for any object in Java using Guava MoreObjects.ToStringHelper() method.
The toString() method in Java returns the string representation of an object, which can be useful for debugging, logging, or displaying information to users. It is very important to implement a meaningful toString() method for your classes. However, writing a good toString() method can be tedious and error-prone, especially if your class has many fields or complex data structures. Fortunately, there is a handy utility class in Google Guava library that can help you with that: MoreObjects.ToStringHelper().
1. Overview of MoreObjects.ToStringHelper() method
Guava MoreObjects.ToStringHelper() is a static factory method that returns an instance of MoreObjects.ToStringHelper class. This class provides a fluent API to build a string representation of an object using key-value pairs. You can use this class to implement the toString() method of your class. The basic usage of this method is as follows:
|
1 2 3 4 |
// Returns "ClassName{x=1}" MoreObjects.toStringHelper(this) .add("x", 1) .toString(); |
In this example, we pass the current object (this) to the toStringHelper() method, which returns an instance of ToStringHelper. Then we chain the add() method calls for each of the fields in the class along with their value. Finally, we call the toString() method to get back the string representation. The output of this method has the format: ClassName{key1=value1, key2=value2, …}. The order of calling these methods is significant, as it determines the order of the fields in the output.
Some of the benefits and features of this method are:
- It automatically uses the simple name of the class as the prefix, unless you specify a different name using the
toStringHelper(String)overload. - It handles
nullvalues gracefully by omitting them from the output, unless you use theaddValue()method instead of add(). - It supports arrays and collections by using
Arrays.toString()andCollections.toString()methods internally. - It allows you to customize the separator,
omitNullValues, andskipNullsoptions using the respective methods in theToStringHelperclass.
2. Usage of MoreObjects.ToStringHelper() method
Let’s see some examples of how to use the Guava MoreObjects.ToStringHelper() method in Java with different scenarios and edge cases.
Example 1: Implementing toString() for a simple class
Let’s say we have a Student class. Each student has a name, id, age, and a list of courses. To create a clear and expressive string representation of our Student class, we pass the current object (this) to the toStringHelper() method, which returns an instance of ToStringHelper. Then we chain the add() method calls for each of the fields in the class along with their value. Finally, we call the toString() method to get back the string representation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import com.google.common.base.MoreObjects; import java.util.List; class Student { private String name; private int id; private int age; private List<String> courses; public Student(String name, int id, int age, List<String> courses) { this.name = name; this.id = id; this.age = age; this.courses = List.copyOf(courses); } // getters and setters omitted for brevity @Override public String toString() { return MoreObjects.toStringHelper(this) .add("name", name) .add("id", id) .add("age", age) .add("courses", courses) .toString(); } } class Main { public static void main(String[] args) { Student s1 = new Student("David", 101, 20, List.of("Math", "Physics", "Chemistry")); Student s2 = new Student("Mia", 102, 21, List.of("Biology", "English", "History")); // Student{name=David, id=101, age=20, courses=[Math, Physics, Chemistry]} System.out.println(s1); // Student{name=Mia, id=102, age=21, courses=[Biology, English, History]} System.out.println(s2); } } |
As you can see, the output of the toString() method is concise and effective, showing the class name and the key-value pairs of the fields. It also handles the array and collection fields by internally using Arrays.toString() and Collections.toString() methods.
Example 2: Generating toString() without field name
Sometimes, you may want to generate a string representation of an object without showing the field name, but only the value. For example, you may want to show only the id of a Student object, or only the name of a Person object. In such cases, you can use the addValue() method instead of add() method in the ToStringHelper class. The addValue() method takes only one argument, which is the value to be added to the string. It does not show the field name in the output.
Let’s see how this works with some sample data. We have a simple Person class that has only one field: name. In the toString() method, we use the addValue() method to add only the name to the string, which does not show the field name in the output.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import com.google.common.base.MoreObjects; class Person { private String name; public Person(String name) { this.name = name; } // getters and setters omitted for brevity @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(name) .toString(); } } class Main { public static void main(String[] args) { Person p1 = new Person("David"); Person p2 = new Person("Mia"); System.out.println(p1); // Person{David} System.out.println(p2); // Person{Mia} } } |
As you can see, the output of the toString() method shows only the class name and the value of the name field. It does not show the key or the field name in the output.
Example 3: Handling null values
One of the advantages of using the Guava MoreObjects.ToStringHelper() method is that it can handles null values gracefully by omitting them from the output. This can be useful when you have optional fields in your class that may or may not have a value. By default, the output of the toString() method does not omit the null values from the output. To omit the null values from the output, you can use the omitNullValues() method in the ToStringHelper class. This method takes no arguments and returns a reference to the ToStringHelper instance.
For example, we have an Employee class that has four fields: name, id, department, and manager. The department and manager fields are optional and may be null for some employees. In order to skip the optional fields when they are null, we call the omitNullValues() method to the ToStringHelper instance.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import com.google.common.base.MoreObjects; class Employee { private String name; private int id; private String department; private String manager; public Employee(String name, int id, String department, String manager) { this.name = name; this.id = id; this.department = department; this.manager = manager; } // getters and setters omitted for brevity @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("name", name) .add("id", id) .add("department", department) .add("manager", manager) .toString(); } } class Main { public static void main(String[] args) { Employee e1 = new Employee("David", 101, "Sales", "Mia"); Employee e2 = new Employee("Michael", 102, null, null); // Employee{name=David, id=101, department=Sales, manager=Mia} System.out.println(e1); // Employee{name=Michael, id=102} System.out.println(e2); } } |
That’s all about Guava MoreObjects.ToStringHelper() method in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)