1、BeanUtil.java
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class BeanUtil
{
private static final String CLASS_PROPERTER = "class";
/**
* 将对象转换成Map
* @param bean 对象
* @return
*/
public static Map getBeanProperty(Object bean)
{
Map returnMap = new HashMap();
PropertyDescriptor[] beanDescriptors = getdescriptors(bean.getClass());
for (int i = 0; i < beanDescriptors.length; i++)
{
//获得属性名称
String propertyName = beanDescriptors[i].getName();
if (propertyName.equals(CLASS_PROPERTER))//过滤 class
{
continue;
}
else
{
try
{ //获得属性值
String propertyValue = (String)beanDescriptors[i].getReadMethod().invoke(bean, null);
if (propertyValue != null)//如果属性值不为空放入map中
{
returnMap.put(propertyName, propertyValue);
}
}
catch (Exception e)
{
returnMap.put(propertyName, null);
e.printStackTrace();
}
}
}
return returnMap;
}
public static PropertyDescriptor[] getdescriptors(Class clazz)
{
BeanInfo beanInfo = null;
try
{ //或得bean类
beanInfo = Introspector.getBeanInfo(clazz);
}
catch (IntrospectionException e)
{
e.printStackTrace();
}
//获得所有的属性描述
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
return descriptors;
}
public static void setBeanPropertyValue(Object setBean, Map valueMap) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
PropertyDescriptor[] beanDescriptors = getdescriptors(setBean.getClass());
for (int i = 0; i < beanDescriptors.length; i++)
{
String propertyName = beanDescriptors[i].getName();
Object propertyValue = valueMap.get(propertyName);
if (propertyValue != null)
{
beanDescriptors[i].getWriteMethod().invoke(setBean, new Object[] { propertyValue });
}
}
}
}
2、TestBeanUtil.java
public class TestBeanUtil {
private String id;
private String name;
private Map map;
public TestBeanUtil(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public static void main(String[] args) {
TestBeanUtil testBeanUtil = new TestBeanUtil("1" ,"李四");
Map map = BeanUtil.getBeanProperty(testBeanUtil);
System.out.println(map);
for (Iterator iter = map.entrySet().iterator();iter.hasNext();){
Map.Entry entry = (Map.Entry) iter.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}
3、运行结果
{name=李四, id=1}
name
李四
id
1
name
李四
id
1