6
I am implementing some generic functions in a module of my system, and I want to treat in a certain situation if the record is numerical (I do calculations).
Then searching some way to do without having to compare with each numerical type separately (Ex: Integer
, Double
, Float
, etc.), I saw that Number
is a base type of all the others (as far as I researched and understood), so this being true, it would be enough to compare the instance of the object to the base type Number
, thus:
// 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 that this is correct and in my test everything seems to be correct, as you can follow here at Ideone.
Questions
- This shape will cover all possible types of numerical objects?
- This way is correct?
- This is the best way to do this check?
Yes, yes and yes. Only the primitive type was left out
char
and its corresponding class wrapperCharacter
.– Piovezan
The guy
char
keeps an integer number in the range from 0 to 65535. Whether it is considered a number for you or not, will depend on your application.– Piovezan
@Piovezan, this one
char
is like aint
16-bit? For theint
is 32 bits and thelong
64 bits, right?– Fernando Leal
@Piovezan, I was checking the other
class
common among them that theCharacter
also implements, which would beComparable
(class Character implements Serializable, Comparable<Character>
), but is String also implements, so the best way to treat theCharacter
together the check is making ainstanceof
extra, something like that:(value instanceof Number || value instanceof Character)
?– Fernando Leal
Yes, it would be a 16-bit int unsigned. And yes, the best way would be as you suggest.
– Piovezan