---
title: "Java中对象（Object）转换成Map"
author: "avanry"
date: "2011-07-04T12:28:44Z"
tags: []
categories: ["编程语言"]
slug: "java-object-map"
draft: false
lastmod: "2011-07-04T12:28:44Z"
id: 1113863
url: "https://avanry.iteye.com/blog/1113863"
---

以前没用过此类方法

1.最简单的转换方法

com.sun.org.apache.commons.beanutils.BeanUtils;

Map map1= new HashMap();

map1 = BeanUtils.describe(要转换的对象);  

 

2.此处转自其它博客，可以参考里面DynaProperty的用法

 

```
package org.apache.commons.beanutils;
import java.beans.PropertyDescriptor; 
import java.lang.reflect.InvocationTargetException; 
import java.util.HashMap; 
import java.util.Map;

/** 
* 
* @since 1.0 
*/ 
public class PageBeanUtilsBean extends BeanUtilsBean { 
@Override 
public Map<String, Object> describe(Object bean) throws IllegalAccessException, InvocationTargetException, 
NoSuchMethodException {

if (bean == null) { 
//            return (Collections.EMPTY_MAP); 
return (new java.util.HashMap<String, Object>()); 
} 
Map<String, Object> description = new HashMap<String, Object>(); 
if (bean instanceof DynaBean) { 
DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); 
for (int i = 0; i < descriptors.length; i++) { 
String name = descriptors[i].getName(); 
description.put(name, getProperty(bean, name)); 
} 
} else { 
PropertyDescriptor[] descriptors = getPropertyUtils().getPropertyDescriptors(bean); 
Class clazz = bean.getClass(); 
for (int i = 0; i < descriptors.length; i++) { 
String name = descriptors[i].getName(); 
if (getPropertyUtils().getReadMethod(clazz, descriptors[i]) != null) { 
description.put(name, getPropertyUtils().getNestedProperty(bean, name)); 
} 
} 
} 
return (description);

} 
}
```