原始类型int实际上如何转换为String?

How is primitive type int actually converted to a String?

首先,我的问题是原始类型 int 如何能够在不成为对象的情况下转换为 String,因此没有 toString() 方法来获取String 值。

我很清楚你是如何能够看似 'convert' 原始类型 int 的变量到 String 在 Java 中。我使用的最简单的方法是:

int x = 5;
String y = "" + x;

效果很好,但我的问题如下:

由于原始类型 int 不是对象,因此没有任何方法,例如 toString() 方法,据我所知,为了获得变量的 String 值,这些方法是必需的。 ..没有这个基本方法怎么识别变量的值?

这叫做字符串转换JLS, Section 5.1.11,指出:

Any type may be converted to type String by string conversion.

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):

(其他类型)

  • If T is byte, short, or int, then use new Integer(x).

然后通过字符串转换将此引用值转换为String类型。

现在只需要考虑参考值:

  • If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

因此,int 转换为 Integer,不是通过装箱转换,而是通过 new Integer(x),然后调用 toString()

从技术上讲,这不是拳击转换;自 Java 开始以来,字符串转换就一直在语言中,其中在 Java 1.5.

中添加了装箱转换

您可以对 static String 使用 valueOf 方法来处理原始类型,例如 int、double、float。部分代码:

int intValue  = 25;
String s = String.valueOf(intValue);

通常,通过调用以下两种方法之一将 int 值转换为 String

对于其他原始值,使用这些方法中的任何一个的相应重载。

StringBuilder.append()

表达式"" + x被编译器实现为:

new StringBuilder().append("").append(x).toString()

x 声明为 int,这意味着将调用采用 int 参数的 append() 的重载。

append(int) 的来源 (Java 1.8.0_65) 是:

@Override
public StringBuilder append(int i) {
    super.append(i);
    return this;
}

super 调用导致:

public AbstractStringBuilder append(int i) {
    if (i == Integer.MIN_VALUE) {
        append("-2147483648");
        return this;
    }
    int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                                 : Integer.stringSize(i);
    int spaceNeeded = count + appendedLength;
    ensureCapacityInternal(spaceNeeded);
    Integer.getChars(i, spaceNeeded, value);
    count = spaceNeeded;
    return this;
}

String.valueOf()

在不使用字符串连接的情况下将值转换为字符串时,通常通过调用 String.valueOf() 来完成。对于表示 valueOf(int):

int
public static String valueOf(int i) {
    return Integer.toString(i);
}

Integer.toString() 调用是:

public static String toString(int i) {
    if (i == Integer.MIN_VALUE)
        return "-2147483648";
    int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
    char[] buf = new char[size];
    getChars(i, size, buf);
    return new String(buf, true);
}

Integer.getChars()

如您所见,两者都是通过实际调用包私有方法来实现的Integer.getChars(int i, int index, char[] buf)

他们都没有实际创建 Integer 的实例,尽管 JLS 暗示它会。