下面实例为用注解实现VO金额字段格式化(若不能用公共方法实现下列,可以采取方法注解和属性注解联合使用,方法注解用AOP拦截实现)
1、自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DecimalFormat {
/**
* 格式
*
* @return 格式
*/
String value();
}
@Retention
注解是 Java 中的一个元注解,用于定义其他注解的保留策略。它指定了被注解的注解在什么阶段仍然有效,主要有以下三种策略:
- SOURCE:注解只保留在源代码中,编译后会被丢弃。
- CLASS:注解会被保留到类文件中,但在运行时不可见。
- RUNTIME:注解会被保留到类文件中,并且在运行时可以通过反射访问。
@Target
注解是 Java 中的一个元注解,用于指定其他注解可以应用于哪些 Java 元素。它定义了注解的适用范围,主要有以下几种类型:
- TYPE:可以应用于类、接口(包括注解)或枚举。
- FIELD:可以应用于字段(包括枚举的常量)。
- METHOD:可以应用于方法。
- PARAMETER:可以应用于方法参数。
- CONSTRUCTOR:可以应用于构造函数。
- LOCAL_VARIABLE:可以应用于局部变量。
- ANNOTATION_TYPE:可以应用于注解类型。
- PACKAGE:可以应用于包。
2、应用注解类
@DecimalFormat("#,##0.######")
private String amount;
3、实现类
public static void setDecimalFormat(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if (field.isAnnotationPresent(DecimalFormat.class) && Objects.nonNull(field.get(obj))
&& org.apache.commons.lang3.StringUtils.isNotEmpty(String.valueOf(field.get(obj)))) {
DecimalFormat annotation = field.getAnnotation(DecimalFormat.class);
field.set(obj, new java.text.DecimalFormat(annotation.value()).format(new BigDecimal(String.valueOf(field.get(obj)))));
}
}
}
4、测试用例
public static void main(String[] args) throws Exception {
TestVO testVO = new TestVO();
testVO.setAmount("1111");
setDecimalFormat(testVO);
System.out.println(testVO.getAmount());
}