问题
I'm trying to make a generic function that takes any type of Number
and conditionally does something if that number is equal to zero. I want anyone to be able to pass it any of the classes that extend Number (BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, or Short)
So far, I've attempted to use instanceof
to find out what type the number is, then compare it to an equivalent type
public static boolean isZero(Number number) {
if (number instanceof BigDecimal) {
return BigDecimal.ZERO.equals(number);
} else if (number instanceof BigInteger) {
return BigInteger.ZERO.equals(number);
} else if (number instanceof Byte) {
return new Byte((byte) 0).equals(number);
} else if (number instanceof Double) {
return new Double(0).equals(number);
} else if (number instanceof Float) {
return new Float(0).equals(number);
} else if (number instanceof Integer) {
return new Integer(0).equals(number);
} else if (number instanceof Long) {
return new Long(0).equals(number);
} else if (number instanceof Short) {
return new Short((short) 0).equals(number);
}
return false;
}
This works, but it is quite long and cumbersome. Is there any way to simplify this?
回答1:
Unfortunately, this is not possible to do in a general way; "Zero" isn't even guaranteed to be representable by a general Number
(because you could e.g. design a "PositiveInteger" class that only represents positive numbers and still adheres to the Number
class spec).
Attempting to convert the value to any other class may cause truncation or rounding, which would invalidate your test, so unfortunately using any method of the Number
class itself will probably produce incorrect results.
来源:https://stackoverflow.com/questions/25252441/if-any-object-of-the-java-abstract-class-number-is-equal-to-zero