我正在阅读 String.java
的源代码在 OpenJDK jdk16u 中。
其构造函数之一如下所示:
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String() {
this.value = "".value;
this.coder = "".coder;
}
显然 .value
指的是这个私有(private)byte
数组:
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
这意味着当我们使用 String() 作为构造函数时, this.value 引用 "".value.
但是,我找不到 "".value
的确切定义。在我看来,这就像一个循环定义。
编辑:这不是循环定义。我的意思是Java如何知道“”表示空字符串。
最佳答案
这是正在构造的对象。由文字“”表示的空字符串是一个已经存在的字符串对象,它与正在构造的对象是分开的。 value 是 String 上的私有(private)字段。该代码将预先存在的空字符串值分配给新对象的值。这里没有循环。
一个对象可以看到另一个对象的私有(private)成员,这有点奇怪,只要另一个对象具有相同的类型,这在类定义中是允许的。通常您会在 equals 方法中看到这一点。
字符串的文字语法被编码到编译器中。不同的 JVM 语言允许不同类型的对象使用不同的文字语法,语法是语言的一部分。 Groovy、Clojure 和 Scala 对于各种事物都有非常不同的文字语法。 https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.10.5 中详细说明了文字规则。
关于java - 关于Java中初始化新创建的空字符串的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68645031/