zoukankan      html  css  js  c++  java
  • bean和map互转

    //自定义注解
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
    public @interface FieldName {
    /** * 字段名 */
    String value() default "";
    /**
    * 是否忽略
    */
    boolean Ignore() default false;
    }

    //map转 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;
    }  
    //bean转map
    public static <T> Map bean2Map(T source) throws IllegalAccessException {
    Map<Object, Object> result = new Properties();
    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) {
    if (field.get(source)!=null)
    result.put(field.getName(), field.get(source));
    } else {
    if (fieldName.Ignore()) continue;
    result.put(fieldName.value(), field.get(source));
    }
    }
    return result;
    }
  • 相关阅读:
    PyCharm不能使用Tab键进行整体向左缩进解决方法
    Python代码规范(PEP8)问题及解决
    Python学习开始
    Spring Annotation(@Autowire、@Qualifier)
    Spring自动装配
    servlet验证码
    Spring集合装配
    帐号明文传输漏洞
    java单元测试
    项目building workspace很慢,或者直接内存溢出的问题解决办法。
  • 原文地址:https://www.cnblogs.com/-mzh/p/mzh.html
Copyright © 2011-2022 走看看