Map與JavaBean相互轉換的工具類
下面就來分享工具類的內容:
使用范圍:JavaBean
類對象的屬性不能是數組、List
、Set
、Map
public class MapBeanUtil { /** * JavaBean轉Map * @param obj * @return */ public static Map<String, Object> bean2Map(Object obj) { Map<String, Object> map = new LinkedHashMap<>(); Class<?> clazz = obj.getClass(); for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); String fieldName = field.getName(); Object value = null; try { value = field.get(obj); } catch (IllegalAccessException e) { e.printStackTrace(); } if (value == null){ value = ""; } map.put(fieldName, value); } return map; } /** * Map轉JavaBean * @param clazz * @param map * @param <T> * @return */ public static <T> T map2Bean(final Class<T> clazz, final Map<String, ? extends Object> map) { if (map == null) { return null; } T res = null; try { res = clazz.getDeclaredConstructor().newInstance(); //獲取到所有屬性,不包括繼承的屬性 Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { //獲取字段的修飾符 int mod = field.getModifiers(); if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) { continue; } //設置對象的訪問權限 field.setAccessible(true); //根據屬性名稱去map獲取value if(map.containsKey(field.getName())) { //給對象賦值 field.set(res, map.get(field.getName())); } } } catch (Exception e) { e.printStackTrace(); } return res; } public static void main(String[] args) throws Exception { HashMap<String, Object> map = new HashMap<>(); map.put("id", 1001); map.put("username", "zhangsan"); map.put("password", "123456"); map.put("nickname", "張三"); map.put("email", "[email protected]"); map.put("gender", true); map.put("birth", LocalDate.now()); map.put("avatar", "/aa/bb/ab.jpg"); map.put("role", "VIP"); map.put("status", (byte) 1); map.put("salt", "ldfkasjghweoiq324"); map.put("createTime", LocalDateTime.now()); map.put("updateTime", LocalDateTime.now()); User user = map2Bean(User.class, map); System.out.println(user); Map<String, Object> res = bean2Map(user); System.out.println(map); } }
User類的代碼:
public class User { private Integer id; private String username; private String password; private String nickname; private String email; private Boolean gender; private LocalDate birth; private String avatar; private String role; private Byte status; private String salt; private LocalDateTime createTime; private LocalDateTime updateTime; }
到此這篇關於Map與JavaBean相互轉換的工具類 的文章就介紹到這瞭,更多相關Map與JavaBean相互轉換內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 使用JavaBean根據指定條件設置屬性值默認值方式
- Java開發反射機制的實戰經驗總結
- 使用JPA自定義VO類型轉換(EntityUtils工具類)
- Java反射技術詳解
- SpringBoot項目如何將Bean註入到普通類中