工具类:Bean与Map转换

package com.yang.util;

import com.yang.pojo.Book;
import org.springframework.cglib.beans.BeanMap;

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

public class BeanUtils extends org.springframework.beans.BeanUtils {
    public BeanUtils() {
    }

    public static <T> T newInstance(Class<?> clazz) {
        return (T) instantiateClass(clazz);
    }

    public static <T> T newInstance(String clazzStr) {
        try {
            Class<?> clazz = Class.forName(clazzStr);
            return newInstance(clazz);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException();
        }
    }

    public static Map toMap(Object src) {
        return BeanMap.create(src);
    }

    public static <T> T toBean(Map<String, Object> beanMap, Class<T> valueType) {
        // 对象实例化
        T bean = BeanUtils.newInstance(valueType);
        PropertyDescriptor[] propertyDescriptors = getPropertyDescriptors(valueType);
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String properName = propertyDescriptor.getName();
            // 过滤class属性
            if ("class".equals(properName)) {
                continue;
            }
            if (beanMap.containsKey(properName)) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (null == writeMethod) {
                    continue;
                }
                Object value = beanMap.get(properName);
                if (!writeMethod.isAccessible()) {
                    writeMethod.setAccessible(true);
                }
                try {
                    writeMethod.invoke(bean, value);
                } catch (Throwable throwable) {
                    throw new RuntimeException("Could not set property '" + properName + " ' to bean" + throwable);
                }
            }
        }
        return bean;
    }

    public static void main(String[] args) {
        // Map To Bean
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("bookID", 1);
        map.put("bookName", "23r");
        map.put("bookCounts", 123);
        map.put("detail", "salt");
        Book book = BeanUtils.toBean(map, Book.class);
        System.out.println(book);

        Map map1 = BeanUtils.toMap(book);
        System.out.println(map1);

    }

}

上一篇:java.lang.NoClassDefFoundError: org/apache/commons/beanutils/BeanUtils


下一篇:Java_jdbc 基础笔记之十二 数据库连接 (beanutils )