java bean与map互相转换

将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 }
原文地址:https://www.cnblogs.com/zh-1721342390/p/8276753.html