map和bean的相互转换

这个地址也可以参考: https://blog.csdn.net/tiantangdizhibuxiang/article/details/80575412

将bean转换为map:

/**
   * 转换bean为map
   *
   * @param source 要转换的bean
   * @param <T>    bean类型
   * @return 转换结果
   */
  public static <T> Map<String, Object> bean2Map(T source) throws IllegalAccessException {
    Map<String, Object> result = new HashMap<>();

    Class<?> sourceClass = source.getClass();
    //拿到所有的字段,不包括继承的字段
    Field[] sourceFiled = sourceClass.getDeclaredFields();
    for (Field field : sourceFiled) {
      field.setAccessible(true);//设置可访问,不然拿不到private
      //配置了注解的话则使用注解名称,作为header字段
      FieldName fieldName = field.getAnnotation(FieldName.class);
      if (fieldName == null) {
        result.put(field.getName(), field.get(source));
      } else {
        if (fieldName.Ignore()) continue;
        result.put(fieldName.value(), field.get(source));
      }
    }
    return result;
  }

将map转换为bean:

/**
   * map转bean
   * @param source   map属性
   * @param instance 要转换成的备案
   * @return 该bean
   */
  public static <T> T map2Bean(Map<String, Object> source, Class<T> instance) {
    try {
      T object = instance.newInstance();
      Field[] fields = object.getClass().getDeclaredFields();
      for (Field field : fields) {
        field.setAccessible(true);
        FieldName fieldName = field.getAnnotation(FieldName.class);
        if (fieldName != null){
          field.set(object,source.get(fieldName.value()));
        }else {
          field.set(object,source.get(field.getName()));
        }
      }
      return object;
    } catch (InstantiationException | IllegalAccessException e) {
      e.printStackTrace();
    }
    return null;
  }

代码中的FieldName类:

 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
 /**
  * 自定义字段名
  * @author Niu Li
  * @since 2017/2/23
  */
 @Retention(RetentionPolicy.RUNTIME)
 @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
 public @interface FieldName {
     /**
      * 字段名
      */
     String value() default "";
     /**
      * 是否忽略
      */
     boolean Ignore() default false;
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值