2016. december 19., hétfő

Custom toString builder for Eclipse




If you are not satisfied the way, how Eclipse generates the toString method for your classes, and you are not so lucky to use the Lombok project, you have the possibility to set custom toString builder for Eclipse.

In the Generate toString dialog you can configure the code style.





By clicking on the Configure button, you can open the Configure Custom toString Builder dialog.




Here you can define the class used for generating the toString method. In the above example I use the ToStringBuilder from Apache Commons (org.apache.commons.lang.builder.ToStringBuilder), but you can implement your own builder class, that meets the requirements.

The generated method looks like this:

    @Override
    public String toString() {
        ToStringBuilder builder = new ToStringBuilder(this);
        builder.append("period", period).append("orderPosition", orderPosition).append("selectable", selectable).append("name_e", name_e);
        return builder.toString();
    }


As I wanted to generate toString in XML and JSON format, I have implemented my own tostring builder classes.

My builders have the advantage, that they do not use reflection, to generate the String representation of the classes. The disadvantage is, that they work only with relative simple classes. But as I try to keep my classes clean and simple, it is not a real problem for my projects.

It is relative easy to implement a class, which satisfies the requirement of a custom Eclipse ToString() Builder. Here is an example, how I created a JSON-like toString() builder class:



Please note, that in order for Eclipse to use the fluent API, for calling the append() method, I needed to implement the Builder Interface.

The configuration of the class to be used as a builder looks like this:




The generated method looks like this:









2 megjegyzés: