問題:前端傳入訪問實體類屬性名稱,按屬性名稱顯示數據,前端傳回的順序是按點擊順序傳回,后端返回的順序是按實體類屬性名稱順序返回。所以需要將前端傳回的實體類屬性名稱進行排序。
示例:
前端傳入數據
["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)); } }); }
顯示結果: