问题:前端传入访问实体类属性名称,按属性名称显示数据,前端传回的顺序是按点击顺序传回,后端返回的顺序是按实体类属性名称顺序返回。所以需要将前端传回的实体类属性名称进行排序。
示例:
前端传入数据
["sex","age","type","orgName"]
实体类User
public class User { private String type; private String orgName; private int age; private String region; private String detailAddress; private String sex; }
排序
// 模拟前端返回数据 List<String> display = new ArrayList<>(); display.add("sex"); display.add("age"); display.add("type"); display.add("orgName"); System.out.println("display = " + display); testUserClass(display); System.out.println("display = " + display); public static void testUserClass(List<String> display){ User user = new User(); Class<? extends User> aClass = user.getClass(); Field[] declaredFields = aClass.getDeclaredFields(); Map<String, Integer> map = new LinkedHashMap<>(); for (int i = 0;i<declaredFields.length;i++) { Field field = declaredFields[i]; map.put(field.getName(),i); } display.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { if (!map.containsKey(o1) || !map.containsKey(o2)){ return 1; } return map.get(o1).compareTo(map.get(o2)); } }); }
显示结果: