Just a note: BigDecimal is not final, so it can be extended with a mutable class. Therefore, in some use cases, a protective copy is required.
You can use the BigDecimal.toString () method:
* 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
Here is a sample code that creates a protective copy of BigDecimal:
public static BigDecimal safeInstance(BigDecimal val) { return val.getClass() == BigDecimal.class ? val : new BigDecimal(val.toString()); }
But does that make sense? If a class extends the BigDecimal class, you cannot be sure that it does not extend its toString () method without abiding by the contract ...
Perhaps it is better to invalidate any BigDecimal extension:
public static BigDecimal safeInstance(BigDecimal val) { if (val.getClass() != BigDecimal.class) {
source share