將bean轉換為map:
1 /** 2 * 轉換bean為map 3 * 4 * @param source 要轉換的bean 5 * @param <T> bean類型 6 * @return 轉換結果 7 */ 8 public static <T> Map<String, Object> bean2Map(T source) throws IllegalAccessException { 9 Map<String, Object> result = new HashMap<>(); 10 11 Class<?> sourceClass = source.getClass(); 12 //拿到所有的字段,不包括繼承的字段 13 Field[] sourceFiled = sourceClass.getDeclaredFields(); 14 for (Field field : sourceFiled) { 15 field.setAccessible(true);//設置可訪問,不然拿不到private 16 //配置了注解的話則使用注解名稱,作為header字段 17 FieldName fieldName = field.getAnnotation(FieldName.class); 18 if (fieldName == null) { 19 result.put(field.getName(), field.get(source)); 20 } else { 21 if (fieldName.Ignore()) continue; 22 result.put(fieldName.value(), field.get(source)); 23 } 24 } 25 return result; 26 }
將map轉換為bean:
1 /** 2 * map轉bean 3 * @param source map屬性 4 * @param instance 要轉換成的備案 5 * @return 該bean 6 */ 7 public static <T> T map2Bean(Map<String, Object> source, Class<T> instance) { 8 try { 9 T object = instance.newInstance(); 10 Field[] fields = object.getClass().getDeclaredFields(); 11 for (Field field : fields) { 12 field.setAccessible(true); 13 FieldName fieldName = field.getAnnotation(FieldName.class); 14 if (fieldName != null){ 15 field.set(object,source.get(fieldName.value())); 16 }else { 17 field.set(object,source.get(field.getName())); 18 } 19 } 20 return object; 21 } catch (InstantiationException | IllegalAccessException e) { 22 e.printStackTrace(); 23 } 24 return null; 25 }
代碼中的FieldName類:
1 import java.lang.annotation.ElementType; 2 import java.lang.annotation.Retention; 3 import java.lang.annotation.RetentionPolicy; 4 import java.lang.annotation.Target; 5 6 /** 7 * 自定義字段名 8 * @author Niu Li 9 * @since 2017/2/23 10 */ 11 @Retention(RetentionPolicy.RUNTIME) 12 @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) 13 public @interface FieldName { 14 /** 15 * 字段名 16 */ 17 String value() default ""; 18 /** 19 * 是否忽略 20 */ 21 boolean Ignore() default false; 22 }