Tuesday, November 11, 2014

How to simply print object content to String in Java

During development, you may frequently want to dump a Java object's all contents into a String for debug and  log.  You object has  fields  of primitive data type as well as List and Set.

In java, dump a object to a more meaningful String will need you to override the toString() method. It's a bad practice to assemble the output string by hand, which is tedious and difficult to maintain. The simplest way to create the output String in the toString() method is using ToStringBuilder class from apache.

1. What you need

  • commons-lang3 package from apache.
You can add the dependency in you maven pom.xml. The current stable version of commons-lang3 is 3.3.2, you can change it to an up-to-date version number.
  <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>


2. Override the toString() in the class definition

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Pet {
int petAge;
String petName;
String petColor;

@Override
public String toString () {
return ToStringBuilder.reflectionToString(this,ToStringStyle.SHORT_PREFIX_STYLE);
}
}


The toString() method is very simple, only need one line. The reflectionToString method will find all the fields in this object and return a String for you automatically. You don't need to assemble the fields one by one. You don't need to care about whether any field's value is null.



3. Run a test main

Let's see run a test main to check the result.
package com.shengwang.demo;

public class DemoMain {

public static void main(String[] args) {

Pet dog = new Pet();
dog.petAge=3;
dog.petName = "snowball";
//dog.petColor = "white";

String output = dog.toString();
System.out.println(output); // print Pet[petAge=3,petName=snowball,petColor=<null>]

}
}


The output looks like "Pet[petAge=3,petName=snowball,petColor=<null>]". For most usage that's good enough.



4.Define your own style (optional)

You may notice there is a prefix of the class name directly before the content of the object("Pet" in our case).If you prefer a more succinct output without that prefix. You can simply define your own style class by extending ToStringStyle from commons-lang3 package.
package com.shengwang.demo;

import org.apache.commons.lang3.builder.ToStringStyle;

public class SuccinctToStringStyle extends ToStringStyle {

private static final long serialVersionUID = 1L;

SuccinctToStringStyle() {
super();
this.setUseClassName(false);
this.setUseIdentityHashCode(false);
this.setUseFieldNames(true);
}
}
Then change in the toString() method to use our own style.
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class Pet {
int petAge;
String petName;
String petColor;

public String toString () {
// use your own style to get even more succinct output
return ToStringBuilder.reflectionToString(this,new SuccinctToStringStyle());
}
}
Run the main again and this time you have output like "[petAge=3,petName=snowball,petColor=<null>]". The prefix class name is gone.

The ToStringBuilder  can handle Java array, List, Set and Map also.  Compare to assemble the String youself, It's simple, clean and maintenance-free!

2 comments:

Powered by Blogger.

About The Author

My Photo
Has been a senior software developer, project manager for 10+ years. Dedicate himself to Alcatel-Lucent and China Telecom for delivering software solutions.

Pages

Unordered List