views:

56

answers:

3

I need to convert array of Objects into a Long/Integer.. Problem is that those Objects are sometimes BigIntegers, sometimes BigDecimals and sometimes even something else. Is there any good libraries for accomplishing this?

for example...

for (Object[] o : result) {
    Long l = SomeClass.convertToLong(o[0]);
    Integer i = SomeClass.convertToInt(o[1]);
}
+1  A: 

For the case of BigInteger and BigDecimal you can just cast that (and all numeric primitive wrapper classes as well) to Number and get the longValue() (be careful when overflowing the range of long 'though).

If they are something else, then you'd need some rules on how to convert it anyway. What "something else" do you have in mind?

Joachim Sauer
+1  A: 

You can get pretty far with Number:

Long l = ((Number) object).longValue();
Integer i = ((Number) object).intValue();
Joonas Pulakka
A: 

The java.lang.Number class and related classes do most of this job just fine. If you need more support for handling nulls and primitives without writing checks and conditionals, check out the Apache Commons-Lang libraries, specifically NumberUtil.class. These are mature, commonly used, and well-documented libraries.

kj