Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 596
fweigl Avatar asked Jan 20 '15 10:01

fweigl


People also ask

How do you check if an object is an instance of a particular class?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do you check if an object is an instance of?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How do you check if an object is a number Java?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

How do I check if an object has a specific property in Java?

The contains(value) method of Properties class is used to check if this Properties object contains any mapping of this value for any key present in it. It takes this value to be compared as a parameter and returns a boolean value as a result.


1 Answers

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.

If you look at the Javadoc for Integer you can see its parent is Number which 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.

like image 148
Peter Lawrey Avatar answered Sep 25 '22 14:09

Peter Lawrey