java – What safe way to check if an object is numeric?


I'm implementing some generic functions in a module of my system, and I want to deal in a certain situation if the register is numeric (I do calculations).

So researching some ways to do it without having to compare with each numeric type separately (Ex: Integer , Double , Float , etc), I saw that Number is a base type of all others (as far as I researched and understood), so this being true , it would be enough to compare the object instance to the base type Number , like this:

// sendo 'value' um Object
if(value instanceof Number){
    // é uma instância de um valor numérico
} else {
    // NÃO é uma instância de um valor numérico

I did some tests, to confirm if this is correct and in my tests everything seems to be correct, as you can see here on Ideone .


  • Will this shape cover all possible types of numeric objects?
  • Is this shape correct?
  • Is this the best way to do this verification?


Yes, this way is correct to check if the type is a Number .

There may be other frills that can help in some specific cases, but basically this is the best way.

But note that it won't cover all numeric types. And actually, in a way, this is not actually possible. Obviously this just checks if the type implements Number , nothing more. If someone creates a numeric type that does not implement this type, it will not be considered.

Of course you will see that this is a design error for the numeric type in question. Then you need to see if this is acceptable or not. I think it's, for me, wrongly implemented types shouldn't be considered at all. And it may not be a mistake, it may be that you have a good reason to do it this way.

Anyway when we inherit from classes or implement interfaces, we are saying something relevant to the code. If there is an external condition that groups certain types together and this cannot be determined in code, it doesn't make much sense to use it in code. And I don't even know if it should exist, even if it's in documentation.

For example, Apache's Complex type doesn't do this.

Scroll to Top