map 与object之间互相转化


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.beanutils.BeanUtils;

/**
* map转成对象
* */
public class MapToObject {
@SuppressWarnings("unused")
private static Logger LOGGER = Logger
.getLogger(MapToObject.class.getName());

public static <T> T mapConvertBean(Class<T> type, Map<String, Object> map) {
T t = null;
try {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
// 获取类属性  
t = type.newInstance();
for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
String propertyName = descriptor.getName();
System.out.println("------------"+propertyName);
if (map.containsKey(propertyName)) {
System.out.println("------------"+map.get(propertyName));
descriptor.getWriteMethod().invoke(t, map.get(propertyName));
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return t;
}

@SuppressWarnings("unchecked")
public static Map<String, Object> beanConvertMap(Object o) {
try {
Map<String, Object> beanMap = BeanUtils.describe(o);
return beanMap;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
}

你可能感兴趣的:(object)