java 检查对象是否是任何“数字”类的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28042626/
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-11-02 12:54:51  来源:igfitidea点击:

Check if object is instance of any 'number' class?

java

提问by fweigl

Object o = ?
if ((o instanceof Integer) || (o instanceof Double) || (o instanceof Float)|| (o instanceof Long))

Is there a shorter version to check if an Object is any of the Number types?

是否有更短的版本来检查对象是否是任何数字类型?

回答by Peter Lawrey

You can do

你可以做

if (o instanceof Number) {
    Number num = (Number) o;

If you only have the class you can do

如果你只有这门课,你可以做

Class clazz = o.getClass();
if (Number.class.isAssignableFrom(clazz)) {

Note: this treats Byte, Short, BigIntegerand BigDecimalas numbers.

注:此治疗ByteShortBigIntegerBigDecimal为数字。

If you look at the Javadoc for Integeryou can see its parent is Numberwhich in turn has the sub-classes AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, DoubleAccumulator, DoubleAdder, Float, Integer, Long, LongAccumulator, LongAdder, Shortso instance Numberwill match any of these.

如果您查看IntegerJavadoc,您会看到它的父类是Number,它又具有子类,AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, DoubleAccumulator, DoubleAdder, Float, Integer, Long, LongAccumulator, LongAdder, Short因此instance Number将匹配其中的任何一个。