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
Check if object is instance of any 'number' class?
提问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
, BigInteger
and BigDecimal
as numbers.
注:此治疗Byte
,Short
,BigInteger
并BigDecimal
为数字。
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, Short
so instance Number
will match any of these.
如果您查看Integer的Javadoc,您会看到它的父类是Number,它又具有子类,AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, DoubleAccumulator, DoubleAdder, Float, Integer, Long, LongAccumulator, LongAdder, Short
因此instance Number
将匹配其中的任何一个。