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?
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With