Just a remark : BigDecimal is not final so it can be extended by a mutable class. Making a defensive copy can therefore be required in some use cases.
The BigDecimal.toString() method can be used :
* There is a one-to-one mapping between the distinguishable
* {@code BigDecimal} values and the result of this conversion.
* That is, every distinguishable {@code BigDecimal} value
* (unscaled value and scale) has a unique string representation
* as a result of using {@code toString}. If that string
* representation is converted back to a {@code BigDecimal} using
* the {@link #BigDecimal(String)} constructor, then the original
* value will be recovered.
Here an example of code making a defensive copy of BigDecimal :
public static BigDecimal safeInstance(BigDecimal val) {
return val.getClass() == BigDecimal.class ?
val : new BigDecimal(val.toString());
}
But does it make sense ? If a class extends the BigDecimal class you cannot be sure it does not extend its toString() method without respecting the contract...
Probably it's better to invalidate any extension of BigDecimal :
public static BigDecimal safeInstance(BigDecimal val) {
if (val.getClass() != BigDecimal.class) {
//TODO throw exception
}
return val;
}