自定义注解
/**
* 自定义注解
*/
@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;
}
}