How do I use Jakarta Commons ToStringBuilder?
Category: Commons Lang, viewed: 2119 time(s).
The toString() method defined in the java.lang.Object can be overriden when we want to give a more meaningful information about our object.
We can simply return any information of the object in the toString() method, for instance the value of object's states or fields.
The Commons Lang library offers a good utility for creating this toString() information. Here I give a simple example using the ToStringBuilder class.
import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; public class ToStringBuilderExample { private String id; private String firstName; private String lastName; public ToStringBuilderExample() {} public String toString() { return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) .append("id", id) .append("firstName", firstName) .append("lastName", lastName) .toString(); } public static void main(String[] args) { ToStringBuilderExample example = new ToStringBuilderExample(); example.id = "1"; example.firstName = "First Name"; example.lastName = "Last Name"; System.out.println("example = " + example); } } |
The result of the code above is:
example = ToStringBuilderExample@addbf1[ id=1 firstName=First Name lastName=Last Name ]
If you want to make the code event more simple, use the line below.
ToStringBuilder.reflectionToString(this);
Using this line the ToStringBuilder will the hard job of finding information of our class and return the string information.
Can't find what you are looking for? Join our FORUMS and ask some questions!
Related Examples
- How do I find text between two strings?
- How do I check for an empty string?
- How do I get the nearest hour, minute, second of a date?
- How do I format date and time using DateFormatUtils class?
- How do I find items in an array?
- How do I use CompareToBuilder class?
- How do I use ReflectionToStringBuilder class?
- How do I convert array of object to array of primitive?
- How do I convert an array to a Map?
- How do I reverse array elements order?
- How do I count word occurrences in a string?
- How do I reverse a string, words or sentences?
- How do I check if a string is empty or not?
- How do I implement equals method using commons-lang?
- How do I implement hashCode using commons-lang?
- How do I convert array of primitives into array of objects?
Most Viewed Examples
Latest Code Examples
Categories
100 Top & Latest
Latest Jobs
Blog Entries
Forums Entries
- Google Chrome
- Re: Importing and scanning the text
- Re: What Java books have you read?
- Re: How to create exe file
- How to create exe file
- Re: What Java books have you read?
- Infix expression
- Importing and scanning the text
- Re: I want to reduce the size of a JPG image
- MOVED: I want to reduce the size of a JPG image
