Java 源代码中为字符串实现的 `+` 在哪里?

Where is `+` implemented for Strings in the Java source code?

String是Java中的特例。它是一个 class,我可以在 source code 中检查它,但它也有自己的中缀运算符 +,这似乎是 StringBuilder 的语法糖。

例如,

"Hello " + yourName;

可能会变成

new StringBuilder().append("Hello ").append(yourName).toString();

Java中没有自定义运算符,所以String中指定的+在哪里?

是否可以使用相同的机制来创建额外的运算符,例如向量?

+ 在 java 编译器 中实现。编译器 String + String 替换为 编译时 常量或 StringBuilder 代码。请注意,这也适用于 primitives。即,int i=1+2 可以在编译过程中直接替换为 int i=3

您可以查看规格。编译器有它的实现,而不是 Java 源代码。

Java Language Specification- 15.18.1. String Concatenation Operator +

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

它显示了实现取决于编译器的证据。

虽然目前大多数 Java 编译器使用 StringBuilder 链,但并未指定应始终采用这种方式。特别是有一个 proposal 可以在 Java-9 中彻底改变这一点,替换为单个 invokedynamic 调用并引入新的元工厂,它将在运行时生成适当的 MethodHandle 来执行连接。

至于语言,不,它是不可扩展的。这是特定行为,没有其他 class 扩展 + 运算符。

至于在哪里做的,请在以下文件中搜索string_add (not a real JVM op)


至于为什么,Java 应该很简单,或者至少比 C++ 简单,并且像字符串操作这样的基本东西是强制性的。但是,运算符重载会增加复杂性。