有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 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

在第二版中,{a1}现在可以解释:

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中的错误


共 (3) 个答案

  1. # 1 楼答案

    本质上,你回答了自己的问题:

    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.

    请注意,左边的操作数不是String类型

  2. # 2 楼答案

    编译器错误是您的javac版本中的一个错误。正如pointed in prior answer这个错误在Java7中已经修复

    参见Sun bug数据库中的egBug ID 7058838

    • 描述:

      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.


    有关背景信息,请参见old 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

  3. # 3 楼答案

    那应该是一个javac错误

    在JavaC7中编译得很好。所以有人报告了它,它被修复了