【发布时间】:2011-11-11 08:13:12
【问题描述】:
在 Java 中给出这个:
String a = "str";
CharSequence b = "charseq";
你可以写
b = b + a;
但不能写入(给出编译器错误)
b += a;
错误是
incompatible types
found : java.lang.CharSequence
required: java.lang.String
现在在 JLS 第二版中,这可以通过 15.26.2 Compound Assignment Operators 中的这一行来解释:
All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.
但在 JLS 第三版中,这条评论消失了,关于复合运算符的唯一说法是15.26.2 Compound Assignment Operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
这似乎不起作用(见上文)。
所以我的问题是 - javac 和 JLS 之间究竟是什么关系,这个特定示例是 javac 中的错误还是 JLS 中的错误?
【问题讨论】:
-
本质上,你回答了你自己的问题:
All compound assignment operators require both operands to be of primitive type, except for +=, which allows the right-hand operand to be of any type if the left-hand operand is of type String.请注意,你是左操作数不是字符串类型 -
是的,但他表示在 JLSv3 中该评论发生了变化,现在执行了演员表。尽管它被声明为 CharSequence,但实际实现是一个字符串,所以如果 JLSv3 中的注释是正确的,它应该转换它并正常工作。
-
您正在测试的 javac 似乎符合 JLSv2 而不是 JLSv3。
-
2 DwB - 对,这就是我得到这个 qn 的原因 - javac 和 JLS 之间的关系是什么。看来jdk6的javac应该符合JLSv3,但显然不符合
-
看起来编译器在这里有一个错误 - 他们的开发人员没有看到这里的规范发生了变化。 (顺便说一句,
Object而不是CharSequence应该会发生同样的情况。)