在Java中输入类型

Tin*_*iny 8 java casting compiler-errors type-conversion

可能重复:
我知道为什么需要在这里将整数文字转换为(int)?

package typecastingpkg;

public class Main
{        
    public static void main(String[] args)
    {
       byte a=10;
       Integer b=(int)-a;
       System.out.println(b);

       int x=25;
       Integer c=(Integer)(-x); // If the pair of brackets around -x are dropped, a compile-time error is issued - illegal start of type.
       System.out.println(c);

       Integer d=(int)-a;     //Compiles fine. Why does this not require a pair of braces around -a?
       System.out.println(d);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,在将-x基本类型int转换为包装类型时Integer,会产生编译时错误:illegal start of type.

Integer c=(Integer)-x;
Run Code Online (Sandbox Code Playgroud)

它需要一对大括号周围的-xInteger c=(Integer)(-x);

但是下面的表达式编译得很好.

Integer d=(int)-a;
Run Code Online (Sandbox Code Playgroud)

为什么这个不像-a前面的表达式那样需要一对括号?

ars*_*jii 11

编译器认为,在表达式中(Integer)-x,您试图x从调用的变量中减去Integer,因此错误,因为没有定义这样的变量.(int)-x因为int是原始类型的保留关键字,并且不能用作变量名,因此编译器可以推断出您尝试强制转换而不是减去.


Viv*_*ath 5

通过检查Java的语法可以找到答案:

CastExpression:
    ( PrimitiveType ) UnaryExpression
    ( ReferenceType ) UnaryExpressionNotPlusMinus
Run Code Online (Sandbox Code Playgroud)

这告诉你,你可以使用一个强制转换表达式,(int) -x;因为它int是一个原始类型,所以你可以有一个跟随它的一元表达式.但是,如果你使用一个对象那么这是一个ReferenceType并且唯一跟随a的东西ReferenceTypeUnaryExpressionNotPlusMinus,它不包括像-x或者+x:

UnaryExpressionNotPlusMinus:
    PostfixExpression
    ~ UnaryExpression
    ! UnaryExpression
    CastExpression
Run Code Online (Sandbox Code Playgroud)

这种禁止的原因是它Integer本身可以被解释为标识符,这会导致歧义.int不能被解释为已识别,因为它是一个保留字.要解决这种歧义,您必须将一元表达式包装在括号中.