您的位置:首页 > 移动开发 > Objective-C

map 与object之间互相转化

2011-09-20 11:03 363 查看
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;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: