JLS如何与Sun javac对应/为什么它们不匹配
作者:互联网
在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中的这一行来解释:
除= =之外,所有复合赋值运算符都要求两个操作数都是基本类型,如果左操作数是String类型,则允许右手操作数为任何类型.
但是在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 bug数据库:
>说明:
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的构建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,javac,jls 来源: https://codeday.me/bug/20190530/1186014.html