使用对象在 java 中自动装箱拆箱

Autoboxing Unboxing in java using Object

使用 Object 类型的对象进行自动装箱是有效的,但它不适用于拆箱。这背后的原因是什么。我的意思是不使用对象类型对象的拆箱功能。是否有任何特殊原因实施此行为。因为它支持自动装箱但不支持 unboxing.When 它涉及 Integer class 它支持自动装箱和拆箱。而且c#也支持Object类型对象的自动装箱和拆箱。

class Demo{
    public static void main(String args[]){

        int x=100;
        Object iob1=new Object();

        Object iob2=x;  //Auto Boxing

        System.out.println(iob2.toString());

        int y = x + iob1;   //Unboxing is not working
        int z = x + new Integer(10); // Unboxing is working
        System.out.println(y);
    }
}

拆箱工作正常。 BUT 仅适用于 DoubleInteger 等。iob1 属于 Object 类型,因此无法使用。 jls 列出的类型可以是 un-/boxed here.

int y = x + iob1;

+ 运算符不能有 intObject(您希望如何向对象添加数字?)。见 this section from the Java Language Specification:

If the type of either operand of a + operator is String, then the operation is string concatenation.

Otherwise, the type of each of the operands of the + operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.