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

利用java反射,将map转换为指定的Object类型

2016-12-23 00:00 561 查看
摘要: 利用java反射,将map转换为指定的Object类型

public interface CommonService<T>  {

public List<T> map2ObjectList(List<Map<String,Object>> maps,Class<T> c)throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException;
}


public class CommonServiceImpl<T> implements CommonService<T>{

@Override
public List<T> map2ObjectList(List<Map<String,Object>> maps,Class<T> c) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
List<T> result = new ArrayList<T>();
for(Map<String,Object> map : maps){
T t = (T) c.newInstance();
Iterator it=map.keySet().iterator();
while(it.hasNext()){
String key = it.next().toString();
String value = map.get(key) == null ? "":map.get(key).toString();
Field field = t.getClass().getDeclaredField(key);//根据属性名获取setter/getter
String type = field.getType().toString();//此属性类型
field.setAccessible(true);//设置些属性是可以访问的
if(type.endsWith("Date")){
if(StringUtils.isNotEmpty(value)){
field.set(t, DateUtil.stringToDate(value, DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS));
}
}else if(type.endsWith("String")){
if(StringUtils.isNotEmpty(value)){
field.set(t, value);
}else{
field.set(t, "");
}
}else if(type.endsWith("int") || type.endsWith("Integer")){
if(StringUtils.isNotEmpty(value)){
field.set(t, Integer.parseInt(value));
}else{
field.set(t, 0);
}
}
}
result.add(t);
}
return result;
}

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