Java如何使用Apache Commons Lang ToStringBuilder类?

在 java.lang.Object 中定义的 toString ()方法。当我们希望提供关于对象的更有意义的信息时,可以重写对象。我们可以简单地返回 toString ()方法中对象的任何信息,例如对象状态或字段的值。

Apache Commons Lang库提供了一个很好的实用程序来创建此toString()信息。在这里,我给出一个使用ToStringBuilder该类的简单示例。

package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

public class ToStringBuilderDemo {
    private Long id;
    private String firstName;
    private String lastName;

    public static void main(String[] args) {
        ToStringBuilderDemo demo = new ToStringBuilderDemo();
        demo.id = 1L;
        demo.firstName = "First Name";
        demo.lastName = "Last Name";

        System.out.println(demo);
    }

    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
            .append("id", id)
            .append("firstName", firstName)
            .append("lastName", lastName)
            .toString();
    }
}

本ToStringStyle类允许我们选择我们的造型toString()方法,当我们把它打印出来。这是我们可以使用的可用样式。

  • ToStringStyle.DEFAULT_STYLE

  • ToStringStyle.JSON_STYLE

  • ToStringStyle.MULTI_LINE_STYLE

  • ToStringStyle.NO_CLASS_NAME_STYLE

  • ToStringStyle.NO_FIELD_NAMES_STYLE

  • ToStringStyle.SHORT_PREFIX_STYLE

  • ToStringStyle.SIMPLE_STYLE

上面代码的结果是:

org.nhooo.example.commons.lang.ToStringBuilderDemo@8efb846[
  id=1
  firstName=First Name
  lastName=Last Name
]

以下是其他示例结果ToStringStyle:

  • ToStringStyle.DEFAULT_STYLE

org.nhooo.example.commons.lang.ToStringBuilderDemo@d716361[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.JSON_STYLE

{"id":1,"firstName":"First Name","lastName":"Last Name"}
  • ToStringStyle.NO_CLASS_NAME_STYLE

[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.NO_FIELD_NAMES_STYLE

org.nhooo.example.commons.lang.ToStringBuilderDemo@d716361[1,First Name,Last Name]
  • ToStringStyle.SHORT_PREFIX_STYLE

ToStringBuilderDemo[id=1,firstName=First Name,lastName=Last Name]
  • ToStringStyle.SIMPLE_STYLE

1,First Name,Last Name

如果要通过使用ToStringBuilder.reflectionToString()方法生成字符串以使toString()方法返回来使代码事件更简单。使用此方法ToStringBuilder将很难找到有关我们类的信息并返回字符串信息。

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>