/** * 把map轉成bean的工具類 * @param map * @param beanCls * @return */ public static <T> T transMap2Bean(Map<String, ?extends Object> map,Class<T> beanCls) { T t = null; try { BeanInfo beanInfo = Introspector.getBeanInfo(beanCls); t = beanCls.newInstance(); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if ("class".equals(key)) { continue; } System.out.println(key); Method setter = property.getWriteMethod(); if (setter.isAnnotationPresent(MethodConverton.class)) { MethodConverton method = setter.getAnnotation(MethodConverton.class); key = method.fieldName(); if (map.containsKey(key)) { Object value = map.get(method.fieldName()); setter.invoke(t, value); } } else { if (map.containsKey(key)) { Object value = map.get(key); // 獲得property對應的setter方法 setter.invoke(t, value); } } } } catch (Exception e) { e.printStackTrace(); System.out.println("transMap2Bean Error " + e); } return t; }
核心代碼貼出來了,相似的,能夠實現一個字符轉換成實體類。java
public class Person { private String name; @MethodConverton(fieldName="username") public void setName(String name) { this.name = name; } public String getName(){ return name; } }
上面這個類裏面用了個自定義的註解用來指定map裏面的屬性和哪一個屬性匹配工具
public class BConvertAnnotation { @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MethodConverton { String fieldName(); } }
自定義了一個註解。
this