How to Convert an Object to String – 如何将对象转换为字符串

最后修改: 2023年 10月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll explore various techniques for converting an object to its string representation in Java.

在本教程中,我们将探讨在 Java 中将对象转换为字符串表示的各种技术。

Converting an object to a string is essential for a multitude of reasons, ranging from displaying object information in a user-friendly format to persisting object data in a readable form.

将对象转换为字符串有许多必要的原因,从以用户友好的格式显示对象信息到以可读的形式持久化对象数据,不一而足。

2. Using toString()

2.使用 toString()

The most straightforward way to convert an object to a string is by using the toString() method. toString() is a built-in method provided by the Object class, which is the root class for all Java objects. Therefore, this method is inherited by all classes, and it returns a String representation of the object.

将对象转换为字符串的最直接方法是使用 toString() 方法。toString()Object 类提供的内置方法,该类是所有 Java 对象的根类。因此,所有类都继承了该方法,它返回对象的 String 表示形式。

However, the default implementation of toString() in the Object class isn’t very informative, as it returns a string that includes the object’s hash code, like, com.baeldung.objecttostring.Person@1f2a0679.

但是,Object 类中的 toString() 的默认实现并不能提供很多信息,因为它会返回一个包含对象哈希代码的字符串,例如:com.baeldung.objecttostring.Person@1f2a0679.

To make this method more useful for our own custom classes, we can override it. By providing our own implementation, we can return a String that represents the object’s data and attributes in a human-readable form.

为了使这个方法对我们自己的自定义类更有用,我们可以覆盖它。通过提供我们自己的实现,我们可以返回一个 String 以人类可读的形式表示对象的数据和属性。

Here’s an example of how we can override the toString() method in a custom class:

下面是一个示例,说明我们如何在自定义类中覆盖 toString() 方法:

public class Person {
    private String name;
    private int age;
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + '}';
    }
}

In this example, the Person class overrides the toString() method to return a String containing the person’s name and age. We can use the toString() method by calling it on an object:

在此示例中,Person 类重载了 toString() 方法,以返回包含个人 nameage 的 String

@Test
public void givenObject_whenToString_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = person.toString();
    assertEquals(expected, actual);
}

3. Using String.valueOf()

3.使用 String.valueOf()

Another simple way to convert an object to a String is by using the String.valueOf() method. This is a static method provided by the String class, which is used to return a string that represents the specified value. This method accepts an object as its argument and returns the string representation of that object. If the object is null, it returns the string “null.

将对象转换为 String 的另一种简单方法是使用 String.valueOf() 方法。这是 String 类提供的一个 static 方法,用于返回表示指定值的字符串。该方法接受一个对象作为参数,并返回该对象的字符串表示。如果对象为 null,则返回字符串”null

Here’s an example of using String.valueOf():

下面是一个使用 String.valueOf() 的示例:

@Test
public void givenObject_whenValueOf_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = String.valueOf(person);
    assertEquals(expected, actual);
}

This results in the string representation of the person object.

这样就得到了人物对象的字符串表示。

4. Using Concatenation

4.使用连接

We can also convert an object to a String through the technique of String concatenation. When an object is joined with an empty string using the addition (+) operator, it yields its string representation:

我们还可以通过 String 连接技术将对象转换为 String 。当使用加法 (+) 运算符将对象与空字符串连接起来时,就会产生其字符串表示形式:

@Test
public void givenObject_whenConcat_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "Person{name='Sarah', age=28}";
    String actual = "" + person;
    assertEquals(expected, actual);
}

5. Using commons-lang3 Library

5.使用 commons-lang3 库

The Apache Commons Lang 3 library offers functionality for the manipulation of fundamental Java API classes. To utilize the Commons Lang 3 library, we simply retrieve it from the central Maven repository by adding the following dependency:

Apache Commons Lang 3 库提供了操作基本 Java API 类的功能。要使用 Commons Lang 3 库,我们只需通过添加以下 依赖关系,从中央 Maven 资源库中获取该库:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

We can use the ToStringBuilder class from this library to build a custom string representation for an object. The ToStringBuilder class allows us to specify which fields of our object we want to include in the string representation.

我们可以使用该库中的 ToStringBuilder 类为对象构建自定义字符串表示法。通过 ToStringBuilder 类,我们可以指定要在字符串表示法中包含对象的哪些字段

Here’s an example of how to use ToStringBuilder to convert an object to a String:

下面是一个如何使用 ToStringBuilder 将对象转换为 String 的示例:

public class Person {
    private String name;
    private int age;

    public String toCustomString() {
        return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
          .append("name", name)
          .append("age", age)
          .toString();
    }
}

In this example, we use ToStringBuilder to create a custom string representation for the Person object in the toCustomString() method. We specify the fields we want to include and the ToStringStyle (e.g., ToStringStyle.JSON_STYLE) for formatting the output:

在本例中,我们使用 toStringBuildertoCustomString() 方法中为 Person 对象创建自定义字符串表示。我们指定了要包含的字段和用于格式化输出的 ToStringStyle (例如,ToStringStyle.JSON_STYLE):

@Test
public void givenObject_whenToStringBuilder_thenConvert() {
    Person person = new Person("Sarah", 28);
    String expected = "{\"name\":\"Sarah\",\"age\":28}";
    String actual = person.toCustomString();
    assertEquals(expected, actual);
}

6. Conclusion

6.结论

In this article, we’ve explored several methods for converting an object to a String in Java.

在本文中,我们探讨了在 Java 中将对象转换为 String 的几种方法。

The choice of method depends on the specific requirements and the complexity of the object we’re working with. It’s crucial to verify that the resulting string effectively conveys the object’s data and aligns with our intended use. With the right approach, we can seamlessly convert objects to strings and improve the readability and usability of our Java applications.

选择哪种方法取决于具体要求和我们所处理对象的复杂程度。关键是要验证生成的字符串是否有效地传达了对象的数据并符合我们的预期用途。通过正确的方法,我们可以将对象无缝转换为字符串,并提高 Java 应用程序的可读性和可用性。

As always, the full source code is available over on GitHub.

一如既往,您可以在 GitHub 上获取完整的源代码