1.map转javaBean
/**
* map转换成javaBean
* @param map
* @return
*/
public static Object transMap2Bean(Map map,Object obj){
try{
//1.获取bean信息
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop: properties) {
String key = prop.getName();
if(map.containsKey(key) && map.get(key) != null){
Object value = map.get(key);
Method setMethod = prop.getWriteMethod();
setMethod.invoke(obj,value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
2.javaBean转map
第一种办法:
/**
* javaBean转换成map
* @param obj
* @return
*/
public static Map transBean2Map(Object obj){
Map map = new HashMap();
try{
//1.获取bean信息
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
if(properties != null && properties.length>0){
for (PropertyDescriptor prop :properties) {
//2.得到属性名
String name = prop.getName();
//3.过滤class属性
if(!"class".equals(name)){
//4.得到属性的get方法
Method getter = prop.getReadMethod();
//5.获取属性值
Object value = getter.invoke(obj);
//6.放入map中
map.put(name,value);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return map;
}
第二种办法:
public static Map transBean2Map2(Object obj){
Map map = new HashMap();
try{
Field[] fields = obj.getClass().getDeclaredFields();
if (fields != null && fields.length > 0){
for (Field field : fields) {
int a = field.getModifiers();
System.out.println(a);
//当属性的修饰符为private时,需要先setAccessible(true)
if (!field.isAccessible()){
field.setAccessible(true);
}
Object value = field.get(obj);
map.put(field.getName(),value);
}
}
}catch(Exception e){
e.printStackTrace();
}
return map;
}
3.利用BeanMap转map的方式
速度快,提供map的接口操作对象
Object get(Object key)
Object put(Object key, Object value)
void putAll(Map t)
Set entrySet()
Collection values()
boolean containsKey(Object key)
……
/**
* 将map装换为javabean对象
* @param map
* @param bean
* @return
*/
public static T mapToBean(Map map,T bean) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}
/**
* bean转Map
* @param
* @return
*/
public static Map bean2Map(T bean){
Map map = new HashMap();
try{
if (bean != null){
BeanMap beanMap = BeanMap.create(bean);
map.putAll(beanMap);
}
}catch (Exception e){
e.printStackTrace();
}
return map;
}