• Bean和Map之间的转换


    import java.beans.BeanInfo;

    import java.beans.IntrospectionException;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;

    import org.apache.commons.beanutils.BeanUtils;//需要引入该jar包

    public class BeanMapUtil {

    //
    public static Object Map2Bean(Class type, Map map)
    throws IntrospectionException, IllegalAccessException,
    InstantiationException, InvocationTargetException {
    //TODO yefangwei
    // ConvertUtils.register(new DateConvert(), Date.class);

    BeanInfo beanInfo = Introspector.getBeanInfo(type);

    Object obj = type.newInstance();

    PropertyDescriptor[] propertyDescriptors = beanInfo
    .getPropertyDescriptors();

    for (int i = 0; i < propertyDescriptors.length; ++i) {
    PropertyDescriptor descriptor = propertyDescriptors[i];
    String propertyName = descriptor.getName();
    if (!(map.containsKey(propertyName.toUpperCase())))
    continue;
    try {
    Object value = map.get(propertyName.toUpperCase());
    BeanUtils.setProperty(obj, propertyName, value);
    } catch (Exception e) {
    }
    }
    return obj;
    }

    //mybatis中传参可以用到

    public static Map bean2Map(Object bean) throws IntrospectionException,
    IllegalAccessException, InvocationTargetException {
    Class type = bean.getClass();
    Map returnMap = new HashMap();
    BeanInfo beanInfo = Introspector.getBeanInfo(type);

    PropertyDescriptor[] propertyDescriptors = beanInfo
    .getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; ++i) {
    PropertyDescriptor descriptor = propertyDescriptors[i];
    String propertyName = descriptor.getName();
    if (!(propertyName.equals("class"))) {
    Method readMethod = descriptor.getReadMethod();
    Object result = readMethod.invoke(bean, new Object[0]);
    if (result != null)
    returnMap.put(propertyName, result);
    else {
    returnMap.put(propertyName, null);
    }
    }
    }
    return returnMap;
    }
    }

  • 相关阅读:
    十一、GUI设计-记事本程序
    十、GUI编程
    OSI七层模型中各层的数据名称
    使用了frame的页面如何整体进行跳转,而不是仅frame跳转
    MySQL脏读、不可重复读、幻读
    博客园后台搜索自己的博客
    完整的ELK+filebeat+kafka笔记
    InnoDB引擎中的索引与算法
    Docker pull下载出现 error pulling image configuration:
    多台服务器通过docker搭建ELK集群
  • 原文地址:https://www.cnblogs.com/xxj-bigshow/p/7601797.html
Copyright © 2020-2023  润新知