1. 程式人生 > 其它 >java反射之-Javabean與Map的互轉

java反射之-Javabean與Map的互轉

1.BeanUntils工具類的準備

/**
 * @ClassName: BeanUtils
 * @Description:
 * @Author: songwp
 * @Date: 9:02 2022/5/19
 **/
public class BeanUtils {

    /**
     * 將javaBean轉換成Map
     * @param bean
     * @return
     * @throws Exception
     */
    public static Map<String,Object> beanToMap(Object bean) throws
Exception { Map<String,Object> map = new HashMap<>(); BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { String name = pd.getName(); Object value
= pd.getReadMethod().invoke(bean); map.put(name,value); } return map; } /** * 將Map轉成javaBean * @param map * @param beanType * @param <T> * @return * @throws Exception */ public static <T> T mapToBean(Map<String,Object> map,Class<T> beanType) throws
Exception { // 建立javaBean物件 Object obj = beanType.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(beanType, Object.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { // 從Map中獲取屬性同名的key值 Object value = map.get(pd.getName()); // 呼叫setter方法設定屬性值 pd.getWriteMethod().invoke(obj,value); } return (T)obj; } }

2.方法測試呼叫

注意:User 和 Person實體需要自己建立(person的屬性和map中的key要有對應)

/**
 * @ClassName: Test9
 * @Description:
 * @Author: songwp
 * @Date: 9:23 2022/5/19
 **/
public class Test9 {
   
    public static void main(String[] args) throws Exception {
        //1.map轉JavaBean
        Map<String,Object> map = new HashMap<>();
        map.put("name","李四");
        map.put("age","28");
        map.put("address","陝西西安");
        Object user1 = BeanUtils.mapToBean(map, Person.class);
        System.out.println(user1);

        System.out.println("================================================================");
        
        //2. javabean轉map
        User user = new User();
        user.setId("10001");
        user.setStatus(0);
        user.setPhone("18740458584");
        user.setNickname("張三");
        Map<String, Object> map1 = BeanUtils.beanToMap(user);
        System.out.println(map1);
    }
}

3.結果如下:

-----------------------------------------------------------------------------
Person(name=李四, age=28, address=陝西西安)
================================================================
{birthday=null, password=null, gender=null, phone=18740458584, nickname=張三, remark=null, id=10001, age=null, status=0, username=null}
-----------------------------------------------------------------------------