JavaRush /Java Blog /Random EN /How to effectively override the ToString() method using T...
dio
Level 16
Москва

How to effectively override the ToString() method using ToStringBuilder.

Published in the Random EN group
ToStringBuilder is a helper class provided by the apache commons lang library . ToStringBuilder is a utility class provided by Apache Commons Lang libraries. It provides complete and better control over what object data and how much should be output by the toString() method, as well as in what format. ToStringBuilder helps you avoid writing a lot of code by eliminating the need to override the ToString() method in child classes. ToStringBuilder can be used to create a template of sorts to take full advantage of the capabilities it provides. To include Commons-Lang in your project, add the following dependencies to your Maven configuration file. In this article, I will give some sample usage examples that can be considered as best practices for overriding the ToString() method in the classes of your next application. To demonstrate the different possibilities of using ToStringBuilder to build the toString() method in different scenarios, I will create three models: AbstractUser.java, WebUser.java and GuestUser.java. commons-lang commons-lang 2.5
AbstractUser.java
package com.howtodoinjava.model; import java.io.Serializable; import org.apache.commons.lang.builder.ToStringBuilder; import com.howtodoinjava.style.CustomToStringStyle; public abstract class AbstractUser implements Serializable { private static final long serialVersionUID = 1L; private int id; private String firstName; private String lastName; private String age; //Setterss and getters }
WebUser.java
public class WebUser extends AbstractUser { private static final long serialVersionUID = 1L; private Date lastLoggedIn; public Date getLastLoggedIn() { return lastLoggedIn; } public void setLastLoggedIn(Date lastLoggedIn) { this.lastLoggedIn = lastLoggedIn; } }
GuestUser.java
public class GuestUser extends WebUser { private static final long serialVersionUID = 1L; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
Various use cases
1) the toString() method in the super class is used by all child classes.
You can override the toString() method in the top-level object class, i.e. in our case AbstractUser.java. This method is used by all child classes unless they contain their own version of the toString() method. @Override public String toString() { return ToStringBuilder.reflectionToString(this); } The above ToString() method is capable of giving all available information about the current class, it will also work in subclasses unless the subclass overrides the ToString() method. package com.howtodoinjava; import java.util.Date; import com.howtodoinjava.model.GuestUser; import com.howtodoinjava.model.WebUser; public class ToStringDemoUsage { public static void main(String[] args) { GuestUser guest = getGuestUser(); System.out.println(guest); } public static GuestUser getGuestUser() { GuestUser user = new GuestUser(); user.setId(100); user.setFirstName("Lokesh"); user.setLastName("Gupta"); user.setAge("30"); user.setLastLoggedIn(new Date()); user.setLocation("New Delhi"); return user; } } Output: com.howtodoinjava.model.GuestUser@d1f24bb[location=New Delhi,lastLoggedIn=Mon Jun 03 13:31:05 IST 2013,id=100,firstName=Lokesh,lastName=Gupta,age=30]
2) Custom formatting of any type, like Data
You can apply a custom format to any field in the ToString method. An example of custom formatting is shown below: package com.howtodoinjava.style; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.lang.builder.ToStringStyle; public class CustomToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; protected void appendDetail(StringBuffer buffer, String fieldName, Object value) { if (value instanceof Date) { value = new SimpleDateFormat("yyyy-MM-dd").format(value); } buffer.append(value); } } To use formatting, place it in a method like this: @Override public String toString() { return ToStringBuilder.reflectionToString(this, new CustomToStringStyle()); } Output: com.howtodoinjava.model.GuestUser@7910769b[location=New Delhi,lastLoggedIn=2013-06-03,id=100,firstName=Lokesh,lastName=Gupta,age=30]
3) Use information from super class in subclass with easy method call
If you want to override ToString() in a child class to add something to the information received from the super class, do it like this: public class WebUser extends AbstractUser { //Other code @Override public String toString() { return new ToStringBuilder(this) .appendSuper(super.toString()) .append("lastLoggedIn", lastLoggedIn).toString(); } } Output: com.howtodoinjava.model.GuestUser@22aed3a5[location=New Delhi,lastLoggedIn=2013-06-03,id=100,firstName=Lokesh,lastName=Gupta,age=30,CustomMessage=I have been added additionally]
4) Use of information only up to a certain level of the inheritance hierarchy
Suppose in some child class you need to expand the fields of all super classes, you can include information up to a certain level of the inheritance hierarchy in the following way: public class GuestUser extends WebUser { @Override public String toString() { return ToStringBuilder.reflectionToString(this,new CustomToStringStyle(),true,WebUser.class); } } Output: com.howtodoinjava.model.GuestUser@18dd7404[location=New Delhi,lastLoggedIn=2013-06-03]
5) Display only the information you want
Sometimes you don't want to include all the fields of a class in the ToString() method. Then you can do it like this: public abstract class AbstractUser implements Serializable { //Other code @Override public String toString() { return new ToStringBuilder(this) .append("firstName", firstName) .append("lastName", lastName) .append("age", age).toString(); } } public class GuestUser extends WebUser { //Other code @Override public String toString() { return new ToStringBuilder(this) .appendSuper(super.toString()) .append("location", location).toString(); } } Output: com.howtodoinjava.model.GuestUser@6483dae1[firstName=Lokesh,lastName=Gupta,age=30,location=New Delhi] You can download the source code of the above examples from this link. Download source Original article: How to override toString() effectively with ToStringBuilder Translated
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION