Java library for converting Object to numeric (Integer, Long, etc.)

I need to convert an array of objects to long / integer. The problem is that these objects are sometimes BigIntegers, sometimes BigDecimals, and sometimes even something else. Are there any good libraries for this?

eg...

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

In the case of BigIntegerand BigDecimalyou can just hide it (and all classes with numeric primitive wrappers) before Numberand get longValue()(be careful when overflowing the range long').

If this is something else, then you will need some rules on how to convert it. What "something else" do you mean?

+2

Number:

Long l = ((Number) object).longValue();
Integer i = ((Number) object).intValue();
+10

The java.lang.Number class and related classes make most of this work just fine. If you need additional support for handling zeros and primitives without writing checks and conditional expressions, check out the Apache Commons-Lang libraries, in particular NumberUtil.class. These are mature, commonly used, and well-documented libraries.

0
source

All Articles