/*/**
* @Author: zmb
* 对象转map
* @param obj
* @Return java.util.Map<java.lang.String,java.lang.Object>
*/
public static Map<String,Object> objectToMap(Object obj){
Map<String,Object> map=new HashMap<String, Object>();
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
try {
/*value为null将value复制为空串*/
if(value.toString().contains("@")){
value=value+"";
}
} catch (Exception e) {
value="";
}
map.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/*/**
* @Author: zmb
* map转对象
* @param map
* @param clz 类名.class
* @Return java.lang.Object
*/
public static Object MapToObject(Map<String,Object> map,Class<?> clz){
if (map == null)
return null;
Object obj = null;
try {
obj = clz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(obj.getClass());
} catch (Exception e) {
e.printStackTrace();
}
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
try {
setter.invoke(obj, map.get(property.getName()));
} catch (Exception e) {
//吃掉map中没有的对象参数异常
}
}
}
return obj;
}
对象和map互转
最新推荐文章于 2024-06-05 16:20:06 发布