为什么Java自动装箱不会扩展到自动装箱类型方法的方法调用? [英] Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?

查看:110
本文介绍了为什么Java自动装箱不会扩展到自动装箱类型方法的方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将原语转换为字符串,我尝试了:

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

myInt.toString();

此操作失败并显示错误:

This fails with the error:

int cannot be dereferenced

现在,我得到的原语不是引用类型(即不是Object)因此不能有方法。然而,Java 5引入了自动装箱和拆箱(一个C#......我在C#中从未喜欢过,但这不是重点)。因此,使用自动装箱,我希望上面的内容将myInt转换为Integer,然后调用toString()。

Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that.

此外,我相信C#允许这样的调用,除非我记错了。这只是Java自动装箱/拆箱规范的一个不幸的缺点,还是有充分的理由呢?

Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?

推荐答案

Java autoboxing /拆箱不会允许您取消引用基元,因此编译器会阻止它。您的编译器仍然知道 myInt 作为基元。在 jcp.org 上有一篇关于此问题的论文。

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);

这篇关于为什么Java自动装箱不会扩展到自动装箱类型方法的方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆