Using Google Guava's Objects.ToStringHelper

前端 未结 6 521
生来不讨喜
生来不讨喜 2021-01-30 10:36

I used ToStringBuilder.reflectionToString(class) in commons-lang, to implement toString() for simple DTOs. Now I\'m trying to use Google Guava instead

6条回答
  •  借酒劲吻你
    2021-01-30 11:14

    In eclipse you can create a template (not as powerfull as IntelliJ https://stackoverflow.com/a/9445402/1301197 ). It will not loop across all member fields for you but you get at least the surrounding code

    windows > preferences > Java > Editor > Templates

    ${:import(com.google.common.base.MoreObjects)}
    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
        .add("${field}",${field})
        .toString();
    }
    

    This will add the import and you will get something like this if you enter id as the field. Then up to you to add the remaining fields.

    public String toString()
    {
        return MoreObjects.toStringHelper(this).add("id", id).toString();
    }
    

    Note that there is probably a better solution by using eclipse toString() generator and creating a custom toString() builder. But this is too much work for a lazy man like me.

    Right click then source > generate toString() and select Custom toString() Builder inside code style.

提交回复
热议问题