Eclipse bug?什么时候短暂不短?

mun*_*ngm 4 java eclipse

这是Eclipse中的错误吗?

声明一个短变量时,编译器将整数文字视为short.

// This works
short five = 5;
Run Code Online (Sandbox Code Playgroud)

但是,当将整数文字作为短参数传递时,它不会执行相同的操作,而是生成编译错误:

// The method aMethod(short) in the type Test is not applicable for 
// the arguments (int)
aMethod(5); 
Run Code Online (Sandbox Code Playgroud)

它清楚地知道整数文字何时超出短期范围:

// Type mismatch: cannot convert from int to short
    short notShort = 655254
Run Code Online (Sandbox Code Playgroud)

-

class Test {
    void aMethod(short shortParameter) {
    }

    public static void main(String[] args) {
        // The method aMethod(short) in the type Test is not applicable for 
        // the arguments (int)
        aMethod(5); 

      // the integer literal has to be explicity cast to a short
      aMethod((short)5);

      // Yet here the compiler knows to convert the integer literal to a short
      short five = 5;
      aMethod(five);


      // And knows the range of a short
      // Type mismatch: cannot convert from int to short
        short notShort = 655254
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:Java原始数据类型.

ass*_*ias 8

这是因为在调用方法时,只授权原始的扩展转换,而不是原始的缩小转换(int - > short).这在JLS#5.3中定义:

方法调用上下文允许使用以下之一:

  • 身份转换(§5.1.1)
  • 扩展的原始转换(第5.1.2节)
  • 扩大参考转换(第5.1.5节)
  • 一个拳击转换(§5.1.7)可选地后面加宽引用转换
  • 一个拆箱转换(第5.1.8节),可选地后跟一个加宽的基元转换.

另一方面,在赋值的情况下,允许缩小转换,只要数字是常数并且适合短,参见JLS#5.2:

如果变量的类型是byte,short或char,则可以使用缩小的基元转换,并且常量表达式的值可以在变量的类型中表示.