David Maki David Maki -3 years ago 98
Java Question

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

My inquiry is on wrapping, using the Object class as my wrapper.

My goal is to take the primitive int (or a wrapper of int) and unbox it from a generic Object.

The only problem is that I will be working with mixed types at runtime, so I am unable to generically type the return type of the method. T var1 != (T) var2

What I can do right now has excessive overhead because I cannot assume the Object wraps a value of type int, so I parse it.

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


This works, but I would ideally like to skip a step of parsing and just unwrap box for the integer value.

Integer wrapper class does not support valueOf(Object o), likely because Object does not implement the relative cast. It (Object) supports toString(). But not toInt(). It is very peculiar because Object indeed can wrap a primitive int. Why that is the case is above my level of knowledge, so I can only work with what I have. For all I know there may even be native support for unwrapping an Object as an int.

Please help me find a solution that involves using minimal parsing and introducing as few exceptions to get the primitive int value.

Answer Source

Misconception on your end:

Object int_wrapped_in_object = 1;

The type of int_wrapped_in_object is Integer, not Object! The compiler already boxes for you!

In other words: there is no way that the java compiler would "box" an int into something that is "only" Object.

Thus a simple int_wrapped_in_object instanceof Integer is all you need to figure if that Object is actually an Integer. And then you can simply cast!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download