I want to dynamically tell if an Object in Java is numeric or not. My code is as the following:
if(obj.getClass().equals(Number.class)) {
attributeTypeStr = "Numeric";
} else {
attributeTypeStr = "Non-Numeric";
}
The Object obj
can be any numeric types like Integer, Float, Double
, etc. But when I tested it with Integer/Float/Double
, the attributeTypeStr
always returns "Non-Numeric"
. I guess that's because Integer/Float/Double
are subclasses of Number
but Number.class
does not equal Double.class
. I could use something like
if(obj.getClass().equals(Integer.class) || obj.getClass().equals(Float.class) || obj.getClass().equals(Double.class))
But it looks too verbose. So is there a simple way to do that?