Eclipse ToString

Posted by Mike Haller on Saturday, May 24. 2008 at 16:44 in Eclipse
This year's Google Summer Of Code 2008 project is sponsoring a new feature for the Eclipse IDE: a ToString generator (See Eclipse Bugzilla 26070). Since there are already two generators in Eclipse JDT for hashCode() and equals() methods (since 3.2), having the third one there, too, would be just natural. Many developers have waited long time for this to come, and I hope we don't have to wait any much longer and that it will make it into the Eclipse Java Development Tools fast.

According to lemmy (the main project mentor), Google has accepted the application of Mateusz, so planning and development can start right away :-)

In fact, there has already been some discussion and the toString() topic might not be as simple as it seems to be at first glance. There is a lot of things to think about.

Most of the time, a String-concatenation is sufficent:
class Customer {
	 int id;
	 String name;
	
	 public String toString() {
		return this.id + "=" + this.name;
	 }
}


However, there is a little bit more behind the toString(). A toString-result is used in many different places. This can be at debug-time for viewing variable values or it can be at runtime for printing out information in logfiles. ToString is also used implicitly when printing out collections.

Many projects use different styles for toString(), just to list the three most commonly used:
- manually, by using concatenated Strings, StringBuilder or String.format()
- Using Commons-Lang ToStringBuilder or Spring's ToStringCreator with method chaining.
- Using Commons-Lang ReflectionToStringBuilder

The latter is the easiest - it's just a one-liner.

public String toString() {
 return ToStringBuilder.reflectionToString(this);
}


The other two's have flexibility but it takes more time to implement them and is a cumbersome task you usually don't want to do manually, except for specific cases.

Another way, similar to StringBuilder, is the use of String.format(), which is clean and readable. The disadvantage of String.format() is that field names and the field variables are far apart. The advantage is that it does not use String concatenation, thus avoids instantiating new String objects, which is expensive.



Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
 
Submitted comments will be subject to moderation before being displayed.
 

About

My name is Mike Haller and I'm a software developer and architect at Bosch Software Innovations in Germany. I love programming, playing games and reading books. I like good food, making photos and learning and mentoring about the craftsmanship of commercial software development. Stack Overflow profile for mhaller

Quicksearch