自定義注解
/*** 自定義注解*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldLabel {// 字段中文String label();// 字段順序int order() default 0;// 分組標識String group() default "default";}
解析自定義注解:
// 1、獲取當前類中聲明的所有字段 2、字段有FieldLabel注解 3、通過group過濾 4、通過order排序List<Field> sortedFields = Arrays.stream(vo.getClass().getDeclaredFields()).filter(f -> f.isAnnotationPresent(FieldLabel.class)).filter(f -> groups.length == 0 || Arrays.asList(groups).contains(f.getAnnotation(FieldLabel.class).group())).sorted(Comparator.comparingInt(f -> f.getAnnotation(FieldLabel.class).order())).collect(Collectors.toList());
應用1:獲取excel表頭
// 構建固定列頭List<List<String>> head = new ArrayList<>();for (Field field : sortedFields) {FieldLabel annotation = field.getAnnotation(FieldLabel.class);head.add(Collections.singletonList(annotation.label()));}
應用2:轉換指定分組的字段,將VO轉為 List<Map<String, String>>:
@Slf4j
public class EntityConverter {public static List<Map<String, String>> convertToJson(Object obj, String... groups) {if (obj == null) {return Collections.emptyList();}List<Field> fields = Arrays.stream(obj.getClass().getDeclaredFields()).filter(f -> f.isAnnotationPresent(FieldLabel.class)).filter(f -> groups.length == 0 || Arrays.asList(groups).contains(f.getAnnotation(FieldLabel.class).group())).sorted(Comparator.comparingInt(f -> f.getAnnotation(FieldLabel.class).order())).collect(Collectors.toList());List<Map<String, String>> items = new ArrayList<>();for (Field field : fields) {try {// 允許通過反射訪問私有(private)或其他受限成員field.setAccessible(true);FieldLabel annotation = field.getAnnotation(FieldLabel.class);Object value = field.get(obj);Map<String, String> item = new LinkedHashMap<>();item.put("label", annotation.label());item.put("value", value != null ? value.toString() : "");items.add(item);} catch (IllegalAccessException e) {log.error("字段轉換出錯,字段:{},錯誤:{}", field.getName(), e.getMessage(), e);throw exception(ProjectErrorCode.ENTITY_CONVERTER_ERROR, e.getMessage());}}return items;}}