[java]
public static <T> T MapToObject(HashMap<String,Object> map,Class<T> class1) throws InstantiationException, IllegalAccessException, IllegalArgumentException, ParseException {
Field[] fields=class1.getDeclaredFields();
T t = null;
if(fields.length>0)
{
t=class1.newInstance();
}
boolean flag;
for (Field field : fields) {
if(map.containsKey(field.getName())&&map.get(field.getName())!=null)
{
flag=false;
if(!field.isAccessible())
{
field.setAccessible(true);
flag=true;
}
if((field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) && map.get(field.getName()).getClass()!=field.getType())
{//时间类型的转换
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
field.set(t,format.parse((String)map.get(field.getName())));
}else if(field.getType() == java.sql.Timestamp.class && map.get(field.getName()).getClass()!=field.getType())
{//Timestamp转换
field.set(t,Timestamp.valueOf((String)map.get(field.getName())));
}else if(field.getType() == java.lang.Long.class &&map.get(field.getName()).getClass()!=field.getType())
{//Long
field.set(t,Long.valueOf((String)map.get(field.getName())));
}else if((field.getType() == int.class || field.getType() == java.lang.Integer.class)&& map.get(field.getName()).getClass()!=field.getType())
{//int
field.set(t,Integer.parseInt((String)map.get(field.getName())));
}else
{
field.set(t,map.get((String)field.getName()));
}
if(flag)
{
field.setAccessible(false);
}
}
}
return t;
}
public static <T> T MapToObject(HashMap<String,Object> map,Class<T> class1) throws InstantiationException, IllegalAccessException, IllegalArgumentException, ParseException {
Field[] fields=class1.getDeclaredFields();
T t = null;
if(fields.length>0)
{
t=class1.newInstance();
}
boolean flag;
for (Field field : fields) {
if(map.containsKey(field.getName())&&map.get(field.getName())!=null)
{
flag=false;
if(!field.isAccessible())
{
field.setAccessible(true);
flag=true;
}
if((field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) && map.get(field.getName()).getClass()!=field.getType())
{//时间类型的转换
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
field.set(t,format.parse((String)map.get(field.getName())));
}else if(field.getType() == java.sql.Timestamp.class && map.get(field.getName()).getClass()!=field.getType())
{//Timestamp转换
field.set(t,Timestamp.valueOf((String)map.get(field.getName())));
}else if(field.getType() == java.lang.Long.class &&map.get(field.getName()).getClass()!=field.getType())
{//Long
field.set(t,Long.valueOf((String)map.get(field.getName())));
}else if((field.getType() == int.class || field.getType() == java.lang.Integer.class)&& map.get(field.getName()).getClass()!=field.getType())
{//int
field.set(t,Integer.parseInt((String)map.get(field.getName())));
}else
{
field.set(t,map.get((String)field.getName()));
}
if(flag)
{
field.setAccessible(false);
}
}
}
return t;
}