What secure way to check if an object is numeric?

6

I am implementing some generic functions in a module of my system, and I want to treat in a certain situation if the registry is numeric (I make calculations).

Then searching some way to do 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 so far as I have researched and understood), then this being true, it would suffice to compare the instance of the object with 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 testing to confirm that this is correct and in my test everything seems to be correct, as you can follow here on Ideone .

Questions

  • Will this form cover all possible types of numeric objects?
  • Is this form correct?
  • Is this the best way to do this?
asked by anonymous 31.07.2015 / 15:19

1 answer

5

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

It may have other firsts that may help in some specific cases, but basically this is the best way.

But note that it will not cover all numeric types. And indeed, in a way, this is not really possible. Obviously this only checks if the type implements the Number , nothing more than this. If someone creates a numeric type that does not implement this type, it will not be considered.

Of course you will see that it is a design error of 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 should not even be considered. And it may not be an error, it may be that you have a good reason to do it this way.

In any case 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 and this can not be determined in code, it does not make much sense to use them in code. And I do not even know if it should exist, even in documentation.

For example, type Complex of Apache does not do this.

    
31.07.2015 / 15:33