java 中为何任何对象都可以和 String 进行拼接?

问题引入

在学习 java-se 中偶然对以下代码产生了兴趣,如下:

1
2
3
4
 String s ="hello" + 123 + true + 1.32;
System.out.println("拼接后的String为:" + s);

//out:拼接后的String为:hello123true1.32

由上可知,任何变量(不管是基本数据类型,还是引用数据类型)都可以自动向 String 进行转换,以完成最后的拼接。那么,这背后的操作是如何实现的呢?

原理剖析

引用数据类型向 String 的转换

引用数据类型,也就是我们常说的类类型,在 java 中都共同拥有一个顶层父类 Object,而在这个 Object 类中,我们可以发现这样一个方法 toString(),其源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Returns a string representation of the object. In general, the
* {@code toString} method returns a string that
* "textually represents" this object. The result should
* be a concise but informative representation that is easy for a
* person to read.
* It is recommended that all subclasses override this method.
* <p>
* The {@code toString} method for class {@code Object}
* returns a string consisting of the name of the class of which the
* object is an instance, the at-sign character `{@code @}', and
* the unsigned hexadecimal representation of the hash code of the
* object. In other words, this method returns a string equal to the
* value of:
* <blockquote>
* <pre>
* getClass().getName() + '@' + Integer.toHexString(hashCode())
* </pre></blockquote>
*
* @return a string representation of the object.
*/
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

通过阅读方法注释,我们不难知道:这个方法是用来输出一个 object 对象的。所有 Java 类都是 object 类的子类,因此所有 Java 对象都具有 toString 方法。

不仅如此,所有 Java 对象都可以和字符串进行连接运算,当 Java 对象和字符串进行连接运算时,系统自动调用 Java 对象 toString () 方法,返回值和字符串进行连接运算。

基本数据类型向 String 的转换

首先,我们知道在 Java 中,一切皆对象,但八大基本类型却不是对象。通过上述分析,我们可以解释对象通过 toString() 转换为字符串后与 String 对象完成拼接,那么基本数据类型又是如何完成这一过程的呢?

要解释这一问题,就要涉及 java 中基本数据类型的自动装箱技术。

所谓装箱,就是把基本类型用它们相对应的引用类型包起来,使它们可以具有对象的特质,如我们可以把 int 型包装成 Integer 类的对象,或者把 double 包装成 Double,等等。

J2SE5.0 后提供了自动装箱与拆箱的功能,此功能事实上是编译器来帮您的忙,编译器在编译时期依您所编写的方法,决定是否进行装箱或拆箱动作

自动装箱的过程:每当需要一种类型的对象时,这种基本类型就自动地封装到与它相同类型的包装中。

通过自动装箱,我们就可以很好的解释为什么基本数据类型 intfloat 等能够完成向 String 的转换与拼接。整个过程就是,编译器检测到我们需要进行 int 与字符串的拼接,首先自动帮我们将 int 自动装箱成 Integer 对象,然后 Integer 对象调用自身的 toString() 方法转为字符串,最终完成拼接工作。

参考文章


Java 包装类 拆箱 装箱

java 打印对象和 toString 方法

Powered By Valine
v1.5.2