开发者

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

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) {
    Lo开发者_StackOverflow中文版ng l = SomeClass.convertToLong(o[0]);
    Integer i = SomeClass.convertToInt(o[1]);
}


You can get pretty far with Number:

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


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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜