简体   繁体   English

在Java中将原始数组转换为Object并返回包含拳击吗?

[英]Does casting a primitive array in Java to an Object and back involve boxing?

Let's say I have the following code: 假设我有以下代码:

class Msg {
    private Object msg;
    public byte[] getMsg() {
        return (byte[]) msg;
    }
    public void setMsg(byte[] msg) {
        this.msg = msg;
    }
}

Does setting and then getting the message involve autoboxing? 设置并获取消息是否涉及自动装箱?

Auto-boxing only occurs when you assign a primitive ( byte ) value (or variable) to a reference ( Byte ) variable. 自动装箱仅在将原始( byte )值(或变量)分配给引用( Byte )变量时发生。

Assigning an array ( byte[] ) to an Object variable only involves casting. 将数组( byte[] )分配给Object变量仅涉及强制转换。 That would be a static or implicit casting. 那将是静态或隐式转换。 Whereas the other way around involves an explicit (dynamic) casting. 而另一种方法涉及显式(动态)转换。

Boxing each element of the array would require creating a whole new array (ie Byte[] ). 将数组的每个元素装箱将需要创建一个全新的数组(即Byte[] )。 And in this case, that's not what's happening. 在这种情况下,这不是正在发生的事情。 You have only chosen to refer to the same array ( byte[] ) just using a variable of type Object . 您仅选择使用Object类型的变量来引用同一数组( byte[] )。

No. Auto-boxing doesn't apply to arrays, at any time. 不可以。自动装箱在任何时候都不适用于阵列。

Even if it did, the array is an object, and it's the reference to array object you're casting, not the elements within it. 即使这样做,数组也是一个对象,它是对您要投射的数组对象的引用,而不是其中的元素。

No. A primitive array is an object. 否。基本数组一个对象。 Both the byte[] and Object references point to the same object. byte []和Object引用均指向同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM