问题描述:在entity包下,需要对返回的字段进行再次的处理,例如对于date字段,需要把date字段转换为指定的格式返回到前端。
解决方案:可以在对应的entity实体类中,加入一个方法,使用注解标注,在返回数据时,利用注解和反射的特性再次进行数据的封装(在这次数据的封装过程中,可以添加分页等一些信息)
解决方案代码用例:
entity类:
class MyEntity {
String id;
String name;
@MyExtendedFiled(name = "namePro")
public String getNamePro() {
return name + " Pro";
}
public MyEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
注解类:
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface MyExtendedFiled {
String name();
}
具体业务实现:
public class TestExtendedFiled {
public static void main(String[] args) throws Exception {
List<MyEntity> list = new ArrayList<>();
MyEntity myEntity = new MyEntity("id 1", "name 1");
list.add(myEntity);
myEntity = new MyEntity("id 2", "name 2");
list.add(myEntity);
List<Map> method = entityToMapPro(list);
String json = JSON.json(method);
//[{"namePro":"name 1 Pro","name":"name 1","id":"id 1"},{"namePro":"name 2 Pro","name":"name 2","id":"id 2"}]
System.out.println(json);
}
/**
* 使用注解和反射,来完成 对entity类中普通字段和注解标记方法字段 的数据封装
*
* @param listEntity
* @return
* @throws IllegalAccessException
*/
private static List<Map> entityToMapPro(List listEntity) throws IllegalAccessException, InvocationTargetException {
List<Map> listMap = new ArrayList<>(listEntity.size());//用于接受新的封装数据
for (Object obj : listEntity) {//遍历每一个entity对象
//判断是否是指定的类
if (!MyEntity.class.isAssignableFrom(obj.getClass())) {
continue;
}
HashMap hashMap = new HashMap<String, Object>();
//将entity中普通字段内容填充到map
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
//field.getName:获取字段名 field.get(obj):获取字段的值
hashMap.put(declaredField.getName(), declaredField.get(obj));
}
//查找并执行使用了注解的方法,并填充数据到map
Method[] declaredMethods = obj.getClass().getDeclaredMethods(); //获取obj本类的所有方法
for (Method declaredMethod : declaredMethods) {
MyExtendedFiled annotation = declaredMethod.getAnnotation(MyExtendedFiled.class);
if (annotation != null) {
// System.out.println(declaredMethod.getName());//获取方法名
//执行该注解标记的方法
Object invoke = declaredMethod.invoke(obj);
hashMap.put(annotation.name(), invoke);//获取方法上注解的赋值名
}
}
listMap.add(hashMap);
}
return listMap;
}
}