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

前端 未结 8 1099
时光取名叫无心
时光取名叫无心 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:01

    It would be helpful if Java defined certain static methods to operate on primitive types and built into the compiler some syntactic sugar so that

    5.asInteger
    

    would be equivalent to

    some.magic.stuff.Integer.asInteger(5);
    

    I don't think such a feature would cause incompatibility with any code that compiles under the current rules, and it would help reduce syntactic clutter in many cases. If Java were to autobox primitives that were dereferenced, people might assume that it was mapping the dereferencing syntax to static method calls (which is effectively what happens in .NET), and thus that operations written in that form were no more costly than would be the equivalent static method invocations. Adding a new language feature that would encourage people to write bad code (e.g. auto-boxing dereferenced primitives) doesn't seem like a good idea, though allowing dereferencing-style methods might be.

提交回复
热议问题