Guava Objects and MoreObjects Tutorial

The Guava Objects and MoreObjects classes provide utilities for a number of common Java idioms.

toString() Utility:

To make writing the standard toString() method less cumbersome, Guava provides a static function MoreObjects.toStringHelper(String className). Utilizing this same utility throughout an application helps provide a standardized and consistent way of implementing the toString() method across classes.

Let’s take a look at an example of how the MoreObjects.toStringHelper() in action:


@Override
public String toString()
{
   return MoreObjects.toStringHelper(this)
          .omitNullValues()
          .add("make", make)
          .add("model", model)
          .add("year", year).toString();
}

Now let’s take a closer look at what’s happening above. To start we pass a reference of the current class into the toStringHelper() method. Next, you see we make a call to omitNullValues(), which excludes any null values and labels from being included in the returned String. Every call to add() provides a label and a value to include in the output.

As you can see, implementing the toString() method in such a way is both trivial and understandable.

[adense]

firstNonNull() Utility:

The method firstNonNull(T first, T second) takes two objects and returns the first non-null object provided. The most common use of firstNonNull() is to provide a way to specify a default value if a method parameter is null. If both objects happen to be null, then a NullPointerException is thrown.

Let’s use the firstNonNull() function in action:


String myUser;

public void setUsername(String username)
{
   myUser = firstNonNull(username, "user not logged in");
}

As you can see in the example above, if the passed in username is null, then the user instance variable will be set to “user not logged in”.

hashCode() Utility:

Properly implementing the hashCode() function, as important as it is, is both error-prone and tedious. Fortunately, Guava provides an easy alternative to this boilerplate code. The Objects.hashCode(Object … objects) method makes it simple as shown below:


@Override
public int hashCode()
{
   return Objects.hash(make, model, year);
}

It really is as simple as that! Simply pass in any appropriate objects or primitives into the function and it will compute the hashCode() without any sort of tricks or magic.