2017-08-15 66 views
0

我的查询是在包装上,使用Object类作为包装。Object是否有本机类型安全的包装和拆箱?

我的目标是采取原始int(或int的包装)并从通用对象中取消它。

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

我现在可以做的事情有过多的开销,因为我不能假设Object包装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()。但是不要到Int()。这是非常奇怪的,因为Object确实可以包装一个原始的int。为什么这种情况超出了我的知识水平,所以我只能用我所拥有的东西来工作。对于我所知道的,甚至可能有本地支持将对象解包为int。

请帮我找一个解决方案,包括使用最少的解析和引入少数例外来获取原始的int值。

+0

请在您需要此类解决方案时提供示例代码。 –

+0

你为什么试图从不包含int的东西中取出一个int? – user2357112

+0

“,以防其值被另一种类型包裹,如字符串”这究竟是什么意思?如果你有一个字符串,那么你没有一个整数值“包装”,它只是一个字符串。 – leonbloy

回答

5

误解你的结尾:

Object int_wrapped_in_object = 1; 

型int_wrapped_in_object的整数,没有对象!编译器已经为你装箱了!

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

因此,一个简单的int_wrapped_in_object instanceof Integer是你所需要的,如果该对象实际上是一个整数。然后你可以简单地

+0

谢谢,我对Object的了解和赞赏更多的要归功于你。我不知道如何将Object超类的自动装箱变成更复杂的包装,所以我只假定它的签名总是只是一个Object。 –

2

您的价值被包裹到一个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,不是如何铸造的作品,只有其观点被降低。您可以检查与

它将打印class java.lang.Integer,而不是class java.lang.Object。所以对象的类型始终保持不变,即使在投射之后。你只能减少对其具有较高模块性等优点的看法。

+1

两个头脑,同样的想法...有我的投票;-) – GhostCat