前言
有个需求在开发的过程中有坑,就记录下顺便也复习,有能优化的地方或别的方案,请在评论指点下我
(查数据部分,没贴,sql自己组装)
![请指教!](https://img-blog.csdnimg.cn/a2437c4732cd4f16bc4792889f0726c1.webp#pic_center)
需求
任务:导出一个word文档,有固定模板,我只需要对着模板查数据并按照前端想要的格式返回
要求格式:
返回对象:
个人信息对象:
个人信息工作经历list<对象>:
······
数据好查,但每个对象中的@Dict需要翻译
思路
数据返回格式已经固定,那么就需要对这些数据进行遍历了,对,还有redis缓存,先从redis中取,空的话再去库中查
对对象进行遍历那只能 用反射进行初步遍历了(不是熟啊~淦),
1、先获取到所有对象(虽然不是每个表都有字典,但是我没在这做判断,直接遍历时把为空的过滤掉)
2、获取到每个对象了,就需要取得每个对象的值
3、因为有对象中有两种类型的对象(对象和List<对象>),所以需要判断两种类型分别进行处理
4、第一种直接用反射直接遍历,获取每个dice的字典值(也就是字典的key)和key所对应的value,
第二种一样需要,只不过是需要先遍历一遍,获取list中所有的对象
5、最后就是拿到字典的code和value就能查唯一个text了
代码
public class test {
public static void main(String[] args) throws IllegalAccessException {
try {
TeacherInfoVO vo = new TeacherInfoVO();
Teacher teachers = new Teacher();
teachers.setSex("1");
vo.setTeachers(teachers);
List<student> tList = new ArrayList<>();
studentt = new student();
t.setId("123");
t.setSex("1");
tList.add(t);
studentt2 = new student();
t2.setId("aaa");
t2.setSex("2");
tList.add(t2);
vo.setStudent (tList);
for (Field field : oConvertUtils.getAllFields(vo)) {
field.setAccessible(true);
Object o = field.get(vo);
if (o instanceof Teachers) {
System.out.println("object 类型判断进入" + o);
getDictText(o);
}
if ("java.util.List".equals(field.getType().getName())) {
List list = (List) field.get(vo);
for (Object obj : list) {
getDictText(obj);
}
}
field.setAccessible(false);
}
} catch (Exception e) {
}
}
public static void getDictText(Object obj) throws IllegalAccessException {
for (Field item : obj.getClass().getDeclaredFields()) {
item.setAccessible(true);
if (item.getAnnotation(Dict.class) != null) {
String code = item.getAnnotation(Dict.class).dicCode();
String value = (String) item.get(obj);
System.out.println("code: " + code + " --- " + "value: " + value);
}
item.setAccessible(false);
}
}
}
打完收工