在 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 中的这一行来解释:
所有复合赋值运算符都要求两个操作数都是基本类型,但 += 除外,它允许如果左侧操作数是字符串类型,则右侧操作数可以是任何类型。
但是在 JLS 第三版中这个注释消失了,关于复合运算符的唯一说法是在 15.26.2 Compound Assignment Operators :
E1 op= E2 形式的复合赋值表达式等同于 E1 = (T)((E1) op (E2)),其中 T 是 E1 的类型,只是 E1 仅计算一次.
这似乎不起作用(见上文)。
所以我的问题是 - javac 和 JLS 之间到底是什么关系,这个特定示例是 javac 中的错误还是 JLS 中的错误?
最佳答案
编译器错误 是您的 javac 版本中的错误。作为pointed in prior answer此错误已在 Java 7 中修复。
参见例如 Bug ID 7058838在 Sun 错误数据库:
描述:
A following function cannot be compiled in java 1.6 or less,. but it can be compiled in java 1.7.
public static void main(String[] args) { Object x = "x"; String y = "y"; x += i; }
- 状态:
不是缺陷 - 评价:
For an Object x and a String y, x+=y is just x=(Object)(x+y). Since y is a String, x undergoes string conversion to produce a string which is concatenated with y, before the no-op cast to Object. The JLS has not changed in this area between SE 6 and SE 7; the program should have been legal for many years.
有关背景,另请参见旧版 Bug Id 4741726
- 描述:
javac used to allow expressions of the form
o += s
where o is a variable of type Object and s is an expression of type String. We fixed that recently (4642850) and this caused a build failure (4741702). Perhaps this is common enough that we should relax the spec instead of fixing the compiler? - 类别:
java:编译器 - 固定发布:
7(b25) - 据我了解,这意味着已在 Java 7 的 build 25 中修复 - 评价:
I'm inclined to relax the spec, though we'd have to know what other implementations do before making a final call on this.
2002-09-04
JLS3 permits Object+=String because the '+' means string concatenation and that is able to concatenate an Object with a String as easily as a String with an Object.
2008-01-31
关于java - JLS如何对应Sun javac/为什么不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7320546/