Java (String) or .toString()? – Java(字符串)或.toString()?

最后修改: 2020年 11月 5日

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

1. Introduction

1.绪论

In this article, we’ll provide a brief explanation of the differences between String casting and executing the toString() method. We’ll briefly review both syntaxes and go through an example explaining the purposes of using each of them. Finally, we’ll take a look at which one is a better approach.

在这篇文章中,我们将简要解释String铸造和执行toString()方法的区别。我们将简要地回顾这两种语法,并通过一个例子来解释使用它们各自的目的。最后,我们将看看哪一种方法更好。

2. String Type Casting and the toString() Method

2.字符串类型转换和toString()方法

Let’s start by making a quick recap. Using the (String) syntax is strictly connected with type casting in Java. In short, the main task of using this syntax is casting a source variable into the String:

让我们先来做个简单的回顾。使用(String)语法与Java中的类型转换严格相关。简而言之,使用该语法的主要任务是将源变量转换为String

String str = (String) object;

As we know, every class in Java is an extension, either directly or indirectly, of the Object class, which implements the toString() method. We use it to get a String representation of any Object:

我们知道,Java中的每个类都是Object类的扩展,它实现了toString()方法。我们用它来获取任何ObjectString表示。

String str = object.toString();

Now that we’ve made a short recap let’s go through some examples to help understand when to use each approach.

现在我们已经做了一个简短的回顾,让我们通过一些例子来帮助理解何时使用每种方法。

3. (String) vs toString()

3.(String) vs toString()

Consider we have an Object variable, and we want to obtain a String. Which syntax should we use?

考虑到我们有一个Object变量,并且我们想获得一个String。我们应该使用哪种语法?

Before moving on, we should emphasize that the following utility method is only used to help explain our topic. In reality, we wouldn’t use utility methods like this.

在继续之前,我们应该强调,下面的实用方法只是用来帮助解释我们的主题。在现实中,我们不会使用这样的实用方法。

Firstly, we let’s introduce a simple utility method to cast an Object into a String:

首先,我们来介绍一个简单的实用方法,将一个Object转换为一个String

public static String castToString(Object object) {
    if (object instanceof String) {
        return (String) object;
    }
    return null;
}

As we can see, before casting, we have to check that our object variable is an instance of a String. If we don’t, it might fail and generate a ClassCastException:

正如我们所看到的,在铸造之前,我们必须检查我们的对象变量是否是字符串的实例。如果我们不这样做,它可能会失败并产生一个ClassCastException

@Test(expected = ClassCastException.class)
public void givenIntegerObject_whenCastToObjectAndString_thenCastClassException() {
    Integer input = 1234;

    Object obj = input;
    String str = (String) obj;
}

However, this operation is null-safe. Using it on a non-instantiated variable, even if it hasn’t been applied to a String variable before, will succeed:

然而,这个操作是不安全的。在一个非实例化的变量上使用它,即使它之前没有被应用于String变量,也会成功。

@Test
public void givenNullInteger_whenCastToObjectAndString_thenSameAndNoException() {
    Integer input = null;

    Object obj = input;
    String str = (String) obj;

    assertEquals(obj, str);
    assertEquals(str, input);
    assertSame(input, str);
}

Now, it’s time to implement another utility function calling toString() on the requested object:

现在,是时候实现另一个实用函数,在被请求的对象上调用toString()

public static String getStringRepresentation(Object object) {
    if (object != null) {
        return object.toString();
    }
    return null;
}

In this case, we don’t need to know the object’s type, and it can be successfully executed on an object without typecasting. We only have to add a simple null check. If we don’t add this check, we could get a NullPointerException when passing a non-instantiated variable to the method:

在这种情况下,我们不需要知道对象的类型,而且不需要类型转换就可以在对象上成功执行。我们只需要添加一个简单的null检查。如果我们不添加这个检查,在向方法传递一个非实例化的变量时,我们可能会得到一个NullPointerException

@Test(expected = NullPointerException.class)
public void givenNullInteger_whenToString_thenNullPointerException() {
    Integer input = null;

    String str = input.toString();
}

Moreover, due to the core String implementation, executing the toString() method on a String variable returns the same object:

此外,由于核心的String实现,在String变量上执行toString()方法会返回同一个对象。

@Test
public void givenString_whenToString_thenSame() {
    String str = "baeldung";

    assertEquals("baeldung", str.toString());
    assertSame(str, str.toString());
}

Let’s get back to our question – which syntax should we use on our object variable? As we’ve seen above, if we know that our variable is a String instance, we should use type casting:

让我们回到我们的问题上来–我们应该对我们的对象变量使用哪种语法?正如我们在上面看到的,如果我们知道我们的变量是一个String实例,我们应该使用类型转换

@Test
public void givenString_whenCastToObject_thenCastToStringReturnsSame() {
    String input = "baeldung";
    
    Object obj = input;
    
    assertSame(input, StringCastUtils.castToString(obj));
}

This approach is generally more efficient and quicker because we don’t need to perform additional function calls. But, let’s remember, we should never pass around a String as an Object. This would hint that we have a code smell.

这种方法通常更有效、更快速,因为我们不需要执行额外的函数调用。但是,让我们记住,我们不应该把一个String作为Object来传递。这将暗示我们有一个代码气味。

When we pass any other object type, we need to call the toString() method explicitly. It is important to remember that it returns a String value according to the implementation:

当我们传递任何其他对象类型时,我们需要明确地调用toString()方法重要的是记住它根据实现返回一个String值。

@Test
public void givenIntegerNotNull_whenCastToObject_thenGetToStringReturnsString() {
    Integer input = 1234;

    Object obj = input;

    assertEquals("1234", StringCastUtils.getStringRepresentation(obj));
    assertNotSame("1234", StringCastUtils.getStringRepresentation(obj));
}

4. Conclusion

4.总结

In this short tutorial, we’ve compared two approaches: String type casting and getting a string representation using the toString() method. Through the examples, we’ve explained the differences and explored when to use (String) or toString().

在这个简短的教程中,我们比较了两种方法。String类型转换和使用toString()方法获得一个字符串表示。通过示例,我们解释了两者的区别,并探讨了何时使用(String)toString()

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

一如既往,文章的完整源代码可在GitHub上获得