Map转javaBean,javaBean转Map
程序员文章站
2024-02-15 19:30:34
...
package com.upincar.dms.commo.utils;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
public class BeanUtils {
/**
* @param map 要转化的Map对象
* @param clazz 要转化成的class
* @return class对应的实例,转化的Object
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
* @throws InstantiationException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object mapToObject(Map map, Class clazz) throws
IllegalAccessException, InvocationTargetException, NoSuchMethodException,InstantiationException {
//获取对象的所有的属性
PropertyDescriptor[] propList = PropertyUtils.getPropertyDescriptors(clazz);
Collection<String> cNames = map.keySet();
//对象转换为Object
Object obj = clazz.newInstance();
for (PropertyDescriptor prop : propList) {
if (prop.getName() != null) {
if (!prop.getPropertyType().equals(Class.class)) {
for (String name : cNames) {
if (nameToUpperCase(prop.getName()).equals(name)) {
//给对象的属性赋值,obj为实例,prop.getName()为实例的某一个属性,map.get(name)为属性的值
PropertyUtils.setProperty(obj, prop.getName(), map.get(name));
}
}
}
}
}
//返回Object
return obj;
}
/**
* JavaBean对象转化成Map对象,有驼峰转换为"_"参数
* @param javaBean
* @param isConvert true把javaBean的驼峰属性转换为带"_"类型的key,false不转换
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map beanToMap(Object javaBean,boolean isConvert) {
Map map = new HashMap();
try {
// 获取javaBean属性
BeanInfo beanInfo = Introspector.getBeanInfo(javaBean.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if (propertyDescriptors != null && propertyDescriptors.length > 0) {
String propertyName = null; // javaBean属性名
Object propertyValue = null; // javaBean属性值
for (PropertyDescriptor pd : propertyDescriptors) {
propertyName = pd.getName();
if (!propertyName.equals("class")) {
Method readMethod = pd.getReadMethod();
propertyValue = readMethod.invoke(javaBean, new Object[0]);
if(isConvert) {//如果是true则把驼峰转换为"_"
propertyName=nameToUpperCase(propertyName);
}
map.put(propertyName, propertyValue);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 作用:驼峰 转为 字符串
* 效果:aaaBbbCcc 转为 AAA_BBB_CCC或者aaa_bbb_ccc
*/
public static String nameToUpperCase(String name) {
StringBuffer sb = new StringBuffer();
if (name != null) {
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if (Character.isUpperCase(c)) {
sb.append("_").append(c);//驼峰 转换为 大写字符,例如: aaaBbbCcc转为 AAA_BBB_CCC
//sb.append(Character.toLowerCase(c)); //驼峰 转换为 小写字符,例如: aaaBbbCcc转为 aaa_bbb_ccc
} else {
sb.append(c);
}
}
}
return sb.toString().toUpperCase();
}
}
上一篇: java 对象转map,map转对象