当前位置: 首页 > news >正文

自定义注解的使用

自定义注解

/*** 自定义注解*/
@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;}}
http://www.dtcms.com/a/265096.html

相关文章:

  • 玄机——某学校系统中挖矿病毒应急排查
  • Redis 常用五大数据类型
  • 【大模型学习 | MINIGPT-4原理】
  • MacOS 安装brew 国内源【超简洁步骤】
  • 数论基础知识和模板
  • Windows下docker安装
  • 通俗易懂的LangGraph图定义解析
  • Git客户端的创建与常用的提交、拉取、修改、推送等命令
  • 【王阳明代数讲义】谷歌编程智能体Gemini CLI 使用指南、架构详解与核心框架分析
  • 带GPU启动 Docker 容器
  • (转)使用DockerCompose部署微服务
  • 使用OpenCV识别图片相似度评分的应用
  • 洪水填充算法详解
  • 基于IndexTTS的零样本语音合成
  • 人脸活体识别4:Android实现人脸眨眼 张嘴 点头 摇头识别(可实时检测)
  • ESP32-s3摄像头驱动开发实战:从零搭建实时图像显示系统
  • sklearn机器学习概述及API详细使用指南
  • LeetCode Hot 100 滑动窗口 【Java和Golang解法】
  • 90.xilinx复位低电平(一般使用低电平复位)
  • 单链表和双向链表
  • python自动化运维
  • Redis基础(2):Redis常见命令
  • 多模态DeepSeek大模型的本地化部署
  • Colormind:优秀大模型赋能国产求解器,打造自主可控建模平台
  • 数学建模_拟合
  • 【Erdas实验教程】026:遥感图像辐射增强(去条带处理)
  • IDEA2025 Version Control 窗口 local changes显示
  • JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
  • 操作系统考试大题-处理机调度算法-详解-2
  • 代码实现特殊的字段的基本功能