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

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 type of number?

+5
source share
1 answer

You can do

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

If you only have a class you can do

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

Note: this applies to Byte , Short , BigInteger and BigDecimal as numbers.

If you look at Javadoc for Integer , you will see that its parent element is Number , which in turn has subclasses AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, DoubleAccumulator, DoubleAdder, Float, Integer, Long, LongAccumulator, LongAdder, Short , so the instance Number will match any of them.

+12
source

Source: https://habr.com/ru/post/1211495/


All Articles