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.
