用于将对象转换为数字(整数、长整数等)的 Java 库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2296099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:29:53  来源:igfitidea点击:

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

javatype-conversion

提问by vrm

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?

我需要将对象数组转换为 Long/Integer .. 问题是这些对象有时是 BigIntegers,有时是 BigDecimals,有时甚至是其他东西。有没有什么好的库可以实现这一点?

for example...

例如...

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

采纳答案by Joachim Sauer

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

对于BigIntegerand的情况,BigDecimal您可以将其(以及所有数字原始包装器类)强制转换为Number并获取longValue()(溢出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?

如果它们是别的东西,那么无论如何你都需要一些关于如何转换它的规则。你想到了什么“别的东西”?

回答by Joonas Pulakka

You can get pretty far with Number:

你可以用Number 走得很远:

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

回答by kj.

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.

java.lang.Number 类和相关类可以很好地完成大部分工作。如果您需要在不编写检查和条件的情况下处理空值和原语的更多支持,请查看 Apache Commons-Lang 库,特别是 NumberUtil.class。这些是成熟的、常用的、文档齐全的库。