JAVA 对象 转 Map

public static void main(String[] args) {

       Student stu = new Student();
       stu.setAge("123");
       stu.setName("456");
       objectToMap(stu); // 对象转map
}

private static void objectToMap(Object obj) {
     Map<String,String> map = new HashMap<String,String>();
     try {
         BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
         PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
         for(PropertyDescriptor property : pds){
             String key = property.getName();
             if(!key.equals("class")){
                 Method getter = property.getReadMethod();
                 Object value = getter.invoke(obj);
                 if(value != null && value.toString().length() > 0){
                     map.put(key,value.toString());
                 }
             }
         }
         System.out.println("map:"+map);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

控制台打印:
map:{name=456, age=123}

猜你喜欢

转载自blog.csdn.net/Zheng_xiao_xin/article/details/81119318
今日推荐