54. Overriding toString()

The toString() method is defined in java.lang.Object, and the JDK comes with a default implementation of it. This default implementation is automatically used for all objects that are the subject of print(), println(), printf(), debugging during development, logging, informative messages in exceptions, and so on.

Unfortunately, the string representation of an object returned by the default implementation is not very informative. For example, let's consider the following User class:

public class User {
private final String nickname;
private final String password;
private final String firstname;
private final String lastname;
private final String email;
private final Date created;

// constructor and getters skipped for brevity
}

Now, let's create an instance of this class, and let's print it on the console:

User user = new User("sparg21", "kkd454ffc",
"Leopold", "Mark", "[email protected]");

System.out.println(user);

The output of this println() method will be something like the following:

The solution for avoiding outputs as in the preceding screenshot consists of overriding the toString() method. For example, let's override it to expose the user details, as follows:

@Override
public String toString() {
return "User{" + "nickname=" + nickname + ", password=" + password
+ ", firstname=" + firstname + ", lastname=" + lastname
+ ", email=" + email + ", created=" + created + '}';
}

This time, println() will reveal the following output:

User {
nickname = sparg21, password = kkd454ffc,
firstname = Leopold, lastname = Mark,
email = [email protected], created = Fri Feb 22 10: 49: 32 EET 2019
}

This is much more informative than the previous output.

But, remember that toString() is automatically called for different purposes. For example, logging can be as follows:

logger.log(Level.INFO, "This user rocks: {0}", user);

Here, the user password will hit the log, and this may represent a problem. Exposing log-sensitive data, such as passwords, accounts, and secret IPs, in an application is definitely a bad practice.

Therefore, pay extra attention to carefully selecting the information that goes in toString(), since this information may end up in places where it can be maliciously exploited. In our case, the password should not be part of toString():

@Override
public String toString() {
return "User{" + "nickname=" + nickname
+ ", firstname=" + firstname + ", lastname=" + lastname
+ ", email=" + email + ", created=" + created + '}';
}

Commonly, toString() is a method generated via an IDE. So, pay attention to which fields you select before the IDE generates the code for you.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.35.255