Automatic Unit Conversion in Java Using Reflection and Custom Annotations
This article explains how to automate repetitive unit‑conversion tasks in Java backend code by first using a map‑based reflection utility and then enhancing it with a custom annotation to declaratively specify conversion types for DTO fields.
When dealing with statistical data, the units often do not match business requirements, requiring frequent conversions such as cents to yuan, percentages, per‑mil, or scaling to ten‑thousands.
The author first proposes a map‑based solution that uses reflection to iterate over DTO fields, checks a provided Map<String, UnitConvertType> for conversion types, and applies the appropriate BigDecimal arithmetic before setting the field value.
Key code snippets include the UnitConvertType enum, the UnitConvertUtil.unitMapConvert method, and a demo main that builds sample data and prints the converted list.
To make the API more declarative, a custom annotation @JcBigDecConvert is introduced, allowing each field to declare its conversion type directly. The unitAnnotateConvert method reads the annotation via reflection and performs the same conversions.
Example DTOs ( MyYearSumReportDTO ) show fields annotated with @JcBigDecConvert , and a second main demonstrates the annotation‑driven conversion producing the expected results.
Both approaches illustrate how reflection and annotations can automate repetitive unit‑conversion logic in backend Java applications.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.