繁体   English   中英

是否存在对象的本机类型安全包装和拆箱?

[英]Is there native type-safe wrapping and unboxing for Object?

我的查询是关于包装,使用Object类作为包装器。

我的目标是获取原始int(或int的包装)并从通用Object中取消装箱。

唯一的问题是,我将在运行时使用混合类型,因此无法通用地键入方法的返回类型。 T var1!=(T)var2

我现在可以做的事情会产生过多的开销,因为我无法假定对象包装了int类型的值,因此我对其进行了解析。

Object int_wrapped_in_object = 1;

Integer.valueOf(String.valueOf(int_wrapped_in_object));

//I could cast from Object to int with:
//(int) int_wrapped_in_object
//but this will always anticipate a classcastexception in case the value was wrapped with another type, like String

这行得通,但理想情况下,我想跳过解析步骤,只打开整数值的包装盒即可。

整数包装器类不支持valueOf(Object o) ,这可能是因为Object没有实现相对转换。 它(对象)支持toString() 但不是toInt()。 这是非常特殊的,因为Object确实可以包装原始int。 为什么是这种情况超出了我的知识水平,所以我只能使用已有的知识。 就我所知,甚至可能存在将对象作为int展开的本机支持。

请帮助我找到一个解决方案,其中涉及使用最少的解析并引入尽可能少的异常来获取原始int值。

对您的误解:

Object int_wrapped_in_object = 1;

int_wrapped_in_object的类型Integer ,而不是Object! 编译器已经为您服务!

换句话说: 没有办法,Java编译器将“盒子”一个int到的东西,是“唯一”的对象

因此,您只需确定一个简单的int_wrapped_in_object instanceof Integer即可确定该Object实际上是一个Integer。 然后您可以简单地投射

您的值将包装到Integer ,然后通过将其强制转换为Object来减小其视图。

如果使用instanceof检查类型,则以后可以安全地将其回退。 然后,您可以使用Integer#intValue方法将其解包装为int

// Indirect conversion int -> Integer and then reduced view to Object
Object int_wrapped_in_object = 5;

if (int_wrapped_in_object instanceof Integer) {
    // Checked cast as the object indeed is an Integer but with reduced view
    Integer intAsInteger = (Integer) int_wrapped_in_object;

    // Retrieve the int value from the Integer
    // (you could also do an implicit unwrapping here) like
    // int value = intAsInteger;
    int value = intAsInteger.intValue();

    System.out.println("The value is: " + value);
} else {
    throw new IllegalStateException("Value is no Integer but it should.");
}

注意行

Object int_wrapped_in_object = 5;

间接转化为

Object int_wrapped_in_object = (Object) Integer.valueOf(5);

如果您经常需要进行此类转换,则只需创建一个实用程序方法即可为您执行此操作。


请注意,对象本身保持Integer且未转换Object ,这不是强制转换的工作方式,仅缩小了其视图。 你可以用

System.out.println(int_wrapped_in_object.getClass())

它将打印class java.lang.Integer而不是class java.lang.Object 因此,即使在投射之后,对象的类型也始终保持不变。 您只需将视图缩小即可,它具有更高的模块化等优点。

暂无
暂无

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

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