You can use a custom annotation in this manner:
The custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FormatBigDecimal {
String format() default "0.00";
}
And then you can apply the annotation on a field and in the constructor call the implementation method as shown below:
public class TestClass {
@FormatBigDecimal
private BigDecimal myDecimal;
public TestClass(BigDecimal myDecimal) throws ParseException, IllegalAccessException {
this.myDecimal = myDecimal;
formatBigDecimalFields();
}
public void setMyDecimal(BigDecimal myDecimal) {
this.myDecimal = myDecimal;
}
public BigDecimal getMyDecimal() {
return myDecimal;
}
/**
In the above method, we are using reflection to get all the fields declared in the class. Then, we are iterating over all the fields and checking whether the @FormatBigDecimal annotation is present on the field. If it is present, we are making the field accessible and getting its value.
We are also getting the format string from the @FormatBigDecimal annotation and using it to create a DecimalFormat object with the desired format. Then, we are formatting the value of the field using the DecimalFormat object and storing the formatted value in a string.
Finally, we are parsing the formatted value back into a BigDecimal object and setting it as the value of the field.
**/
public void formatBigDecimalFields() throws IllegalAccessException, ParseException {
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(FormatBigDecimal.class)) {
field.setAccessible(true);
BigDecimal value = (BigDecimal) field.get(this);
FormatBigDecimal formatAnnotation = field.getAnnotation(FormatBigDecimal.class);
String formatString = formatAnnotation.format();
NumberFormat format = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat decimalFormat = (DecimalFormat) format;
decimalFormat.applyPattern(formatString);
String formattedValue = decimalFormat.format(value);
BigDecimal formattedDecimal = new BigDecimal(formattedValue);
field.set(this, formattedDecimal);
}
}
}
}
To Use it:
TestClass testClass = new TestClass(new BigDecimal("10000.899"));
System.out.println(testClass.getMyDecimal());
will give: 10000.90