一、概述
最近开发工作中,需要将类中的所有字段获取出来,并转换为json字符串,予以存储起来,用于poi excel导出,可以根据实际需要,增、减字段,来调整导出列的需求。 本文将 使用 反射的方式,获取类中的字段,存储到map中,再使用Fastjson转换为json字符串,用于输出存储。
二、代码实现
1、依赖 pom
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>fastjsonartifactId>
- <version>1.2.83version>
- dependency>
-
- <dependency>
- <groupId>io.springfoxgroupId>
- <artifactId>springfox-swagger2artifactId>
- <version>2.9.2version>
- dependency>
-
- <dependency>
- <groupId>io.springfoxgroupId>
- <artifactId>springfox-swagger-uiartifactId>
- <version>2.9.2version>
- dependency>
2、代码
- /**
- * Description: 生成类的字段 映射 map
- * @param clz 转换类的 class 对象
- * @param excludeList 排除的字段名
- * @param clzAnon 注解名 --- 用于字段 注释信息获取
- * @return java.util.List
> - * @version v1.0
- * @author wu
- * @date 2022/9/26 21:04
- */
- public
List - List
fieldList = Arrays.stream(clz.getDeclaredFields()).collect(Collectors.toList()); - List
- int n = 1;
- for (Field f : fieldList) {
- String name = f.getName();
- if (CollectionUtils.isNotEmpty(excludeList)) {
- if (excludeList.contains(name)) continue;
- }
-
- HashMap
tempMap = Maps.newHashMap(); - Annotation annotation = f.getAnnotation(clzAnon);
- String colName = name;
- if (annotation instanceof ApiModelProperty) {
- ApiModelProperty a = (ApiModelProperty) annotation;
- colName = a.value();
- }
- // add more Annotation support ...
-
- tempMap.put("colIndex", "" + n ++);
- tempMap.put("colName", colName);
- tempMap.put("property", name);
-
- mapList.add(tempMap);
- }
- return mapList;
- }
3、测试
- @Test
- public void genPropertyMap(){
- ArrayList
list = Lists.newArrayList(); - list.add("num22"); // 过滤掉属性num22
- List
- System.out.println("propertyMap: \n"+ JSON.toJSONString(propertyMap));
- }
3.1、输出结果如下:
- propertyMap:
- [
- {
- "colIndex": "1",
- "colName": "id2号",
- "property": "id22"
- },
- {
- "colIndex": "2",
- "colName": "名字2号",
- "property": "name22"
- },
- {
- "colIndex": "3",
- "colName": "地址2号",
- "property": "addr22"
- }
- ]
4、补充:Child 类结构如下
- public class Child {
-
- @ApiModelProperty(value = "id2号")
- public int id22 ;
-
- @ApiModelProperty(value = "数字2号")
- protected int num22 ;
-
- @ApiModelProperty(value = "名字2号")
- String name22 ;
-
- @ApiModelProperty(value = "地址2号")
- private String addr22;
-
- // ignore getter/setter
- }
三、总结
1、获取一个类中的所有字段,可以使用反射来实现; 转换json字符串,可以使用 Fastjson、Gson、Jackson 等工具类实现 ..
2、关于反射,注解等相关的知识,可以参考:
3、idea 方法注释模板设置: Idea 设置方法注释模板 Idea 2021.2配置方法类注释模板_HaHa_Sir的博客-CSDN博客_idea设置方法注释模板