Java 中 Map与JavaBean实体类之间的相互转化

本文介绍了如何将JavaBean对象转换为Map对象以及如何将Map对象转换回JavaBean的方法。通过使用Introspector和PropertyDescriptor等类,实现了JavaBean属性到Map键值对的映射。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
* 将一个 JavaBean 对象转化为一个 Map
* @param bean 要转化的JavaBean 对象
* @return 转化出来的 Map 对象
* @throws IntrospectionException 如果分析类属性失败
* @throws IllegalAccessException 如果实例化 JavaBean 失败
* @throws InvocationTargetException 如果调用属性的 setter 方法失败
*/
@SuppressWarnings({ “rawtypes”, “unchecked” })
public static Map convertBean(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, "");    
            }    
        }    
    }    
    return returnMap;    
}  

/**
* 将一个 Map 对象转化为一个 JavaBean
* @param type 要转化的类型
* @param map 包含属性值的 map
* @return 转化出来的 JavaBean 对象
* @throws IntrospectionException 如果分析类属性失败
* @throws IllegalAccessException 如果实例化 JavaBean 失败
* @throws InstantiationException 如果实例化 JavaBean 失败
* @throws InvocationTargetException 如果调用属性的 setter 方法失败
*/
@SuppressWarnings(“rawtypes”)
public static Object convertMap(Class type, Map map)
throws IntrospectionException, IllegalAccessException,
InstantiationException, InvocationTargetException {
BeanInfo beanInfo = Introspector.getBeanInfo(type); // 获取类属性
Object obj = type.newInstance(); // 创建 JavaBean 对象

    // 给 JavaBean 对象的属性赋值    
    PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();    
    for (int i = 0; i< propertyDescriptors.length; i++) {    
        PropertyDescriptor descriptor = propertyDescriptors[i];    
        String propertyName = descriptor.getName();    

        if (map.containsKey(propertyName)) {    
            // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。    
            Object value = map.get(propertyName);    

            Object[] args = new Object[1];    
            args[0] = value;    

            descriptor.getWriteMethod().invoke(obj, args);    
        }    
    }    
    return obj;    
}  
以下是Java中将Map转换为实体类的示例代码: ```java public class EntityMapUtils { /** * 将一个 Map对象转化JavaBean * * @param map 包含属性值的map * @param beanClass 要转化成的类 * @return 转化出来的JavaBean对象 */ public static <T> T mapToEntity(Map<String, Object> map, Class<T> beanClass) throws Exception { // 创建 JavaBean 对象 T obj = beanClass.newInstance(); // 获取类中所有的属性集合 Field[] fields = obj.getClass().getDeclaredFields(); // 遍历属性集合,将属性值从map中赋值给JavaBean对象 for (Field field : fields) { // 获取属性名 String fieldName = field.getName(); // 获取属性值 Object fieldValue = map.get(fieldName); // 如果属性值不为空,则将属性值赋值给JavaBean对象 if (fieldValue != null) { field.setAccessible(true); field.set(obj, fieldValue); } } return obj; } /** * 将实体类转换为Map * * @param obj 要转化实体类 * @return 转化出来的Map对象 */ public static Map<String, Object> entityToMap(Object obj) throws Exception { // 创建Map对象 Map<String, Object> map = new HashMap<>(); // 获取类中所有的属性集合 Field[] fields = obj.getClass().getDeclaredFields(); // 遍历属性集合,将属性值从JavaBean对象中取出并存入Map对象中 for (Field field : fields) { // 获取属性名 String fieldName = field.getName(); // 获取属性值 field.setAccessible(true); Object fieldValue = field.get(obj); // 如果属性值不为空,则将属性值存入Map对象中 if (fieldValue != null) { map.put(fieldName, fieldValue); } } return map; } } ``` 使用示例: ```java // 定义一个实体类 public class User { private String name; private int age; public User() { } public User(String name, int age) { this.name = name; this.age = age; } // 省略getter和setter方法 } // 将Map转换为实体类 Map<String, Object> map = new HashMap<>(); map.put("name", "张三"); map.put("age", 20); User user = EntityMapUtils.mapToEntity(map, User.class); // 将实体类转换为Map User user = new User("张三", 20); Map<String, Object> map = EntityMapUtils.entityToMap(user); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值