---
title: "Lombok 之 ToString"
author: "朱秋旭"
date: "2014-10-02T11:43:15Z"
tags: ["Java", "annotation", "lombok"]
categories: ["互联网"]
slug: "lombok-tostring"
draft: false
lastmod: "2014-10-03T15:28:54Z"
id: 2124349
url: "https://himichaelchu.iteye.com/blog/2124349"
---

LomBok 的相关目录已经整理出来，希望大家可以根据需求自助学习，好工具要大家分享：

[@Cleanup](/admin/blogs/2124327)     

[@Getter, @Setter](/admin/blogs/2124335)

[@ToString](/blog/2124349)

[@EqualsAndHashCode](/admin/blogs/2124353)

[@Constructor](/blog/2124409)

[@Data & @Value](/blog/2124577)

[@](/admin/blogs/2124582)[SneakyThrows](/admin/blogs/2124582)

[@Synchronized](/admin/blogs/2124584)

[@Getter(lazy=true)](/admin/blogs/2124588)

[@Log](/admin/blogs/2124589)

 

很多时候我们进行一些探索和功能验证的时候，需要用到当前对象的toString方法，尤其是在进行xml解析，json解析这样的功能验证的时候，之前工作中就遇到过需要解析xml 和json，如果每次验证都启动tomcat的话会非常的消耗时间，所以索性直接Override toString方法，然后测试功能。

对于重写toString方法这件事大多数的做法都是把变量按照顺序，用提示语句区分，逐个打印出来，不知道屏幕前的小伙伴有多少为了这样事情苦恼的。因为写这样的代码实在头疼，又要关注拼接字符串的格式。在Lombok中，一个@ToString annotation很好的解决了这个问题。让我们一起来看一个例子：

我们的代码经常这样：

 

```
import java.util.Arrays;

public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  public static class Square extends Shape {
    private final int width, height;
    
    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
    
    @Override public String toString() {
      return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
    }
  }
  
  @Override public String toString() {
    return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  }
}
```

 

其实，我们的代码可以这样：

 

```
import lombok.ToString;

@ToString(exclude="id")
public class ToStringExample {
  private static final int STATIC_VAR = 10;
  private String name;
  private Shape shape = new Square(5, 10);
  private String[] tags;
  private int id;
  
  public String getName() {
    return this.getName();
  }
  
  @ToString(callSuper=true, includeFieldNames=true)
  public static class Square extends Shape {
    private final int width, height;
    
    public Square(int width, int height) {
      this.width = width;
      this.height = height;
    }
  }
}
```

 这样的方便方式节省了好多拼接字符串的功夫。

 

`lombok.toString.includeFieldNames` = \[`true` | `false`] (default: true)

是否包含field的信息，如果值为true ，则可以在toString方法中给出field 的name。

`lombok.toString.doNotUseGetters` = \[`true` | `false`] (default: false)

如果值为true，则Lombok会直接获取field 而不是通过get方法获取值。