Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?

前端 未结 8 1030
时光取名叫无心
时光取名叫无心 2020-12-30 18:19

I want to convert a primitive to a string, and I tried:

myInt.toString();

This fails with the error:

int cannot be derefere         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-30 19:03

    Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows myInt as a primitive. There's a paper about this issue at jcp.org.

    Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa).

    So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way)

    Integer.toString(myInt);
    

提交回复
热议问题