Thursday, April 10, 2008

toString() methods generation

If you want to generate quick a toString() method for your domain-objects, with all the attributes and relative values a good solution is the eclipse plug-in jutils.

Anyway, if your are doing some refactoring, there some probability that you will forget to add new or renamed fields to your toString() method... but don't care!
The people of GridGain have thought a very clever solution to this common issue.
You can simply write a generic impementation as follows
     @Override  
public String toString() {
return ToStringBuilder.toString(MySimpleClass.class, this);
}

to obtain the desired result.
Besides you have also the flexibility to exclude/include attribute or set the right order by using the following annotaions:

  • @GridToStringInclude Annotation This annotation can be attached to any field in the class to make sure that it is automatically included even if it is excluded by default.

  • @ToStringExclude AnnotationThis annotation can be attached to any field in the class to make sure that it is automatically excluded even if it is included by default.

  • @ToStringOrder(int) Annotation This annotation provides custom ordering of class fields. Fields with smaller order value will come before in toString() output. By default the order is the same as the order of field declarations in the class.

This ingenious approach can also be extended to generate XML or JSON rapresentation of a domain object.

No comments: