项目中用到的,list转换成bean。因为查询出来的数据用list 泛型接收,要返回 实体对象。所以需要对应转换。
主要用到的技术:反射。
上代码:
public static <T> List<T> toBean(List<?> list, Class<T> clz) {
int count = 0;
Field[] fields = clz.getDeclaredFields();
List<T> lst = new ArrayList();
String propertyName = "";
Object obj = null;
try {
for(int i = 0; i < list.size(); ++i) {
obj = clz.newInstance();
Object[] oo = (Object[])list.get(i);
Field[] var12 = fields;
int var11 = fields.length;
for(int var10 = 0; var10 < var11; ++var10) {
Field fd = var12[var10];
Type t = fd.getGenericType();
String className = t.toString().replace("class", "");
Class<?> type = Class.forName(className.trim());
propertyName = "set" + change(fd.getName());
Method mt = obj.getClass().getMethod(propertyName, new Class[]{type});
if(!"java.lang.String".equals(className.trim())) {
if("java.lang.Integer".equals(className.trim())) {
mt.invoke(obj, new Object[]{Integer.valueOf(Integer.parseInt(oo[count] == null?"-1":oo[count].toString()))});
} else if("java.lang.Long".equals(className.trim())) {
mt.invoke(obj, new Object[]{Long.valueOf(Long.parseLong(oo[count] == null?"-1":oo[count].toString()))});
} else {
Clob clobs;
if("java.sql.Date".equals(className.trim())) {
Date date = (Date)oo[count];
if(!"".equals(date) && date != null) {
java.sql.Date sd = new java.sql.Date(date.getTime());
mt.invoke(obj, new Object[]{sd});
} else {
clobs = null;
mt.invoke(obj, new Object[]{clobs});
}
} else if("oracle.sql.CLOB".equals(className.trim())) {
if(oo[count] == null) {
mt.invoke(obj, new Object[1]);
} else {
SerializableClobProxy sc = (SerializableClobProxy)Proxy.getInvocationHandler(oo[count]);
clobs = sc.getWrappedClob();
CLOB clob = (CLOB)clobs;
mt.invoke(obj, new Object[]{clob});
}
} else {
mt.invoke(obj, new Object[]{oo[count]});
}
}
} else {
String s = "" + oo[count];
if(s == null || "null".equals(s)) {
s = "";
}
mt.invoke(obj, new Object[]{s});
}
++count;
}
count = 0;
lst.add((T)obj);
}
} catch (SecurityException var20) {
logger.error(var20.getMessage());
} catch (IllegalArgumentException var21) {
logger.error(var21.getMessage());
} catch (InstantiationException var22) {
logger.error(var22.getMessage());
} catch (IllegalAccessException var23) {
logger.error(var23.getMessage());
} catch (ClassNotFoundException var24) {
var24.printStackTrace();
logger.error(var24.getMessage());
} catch (NoSuchMethodException var25) {
logger.error(var25.getMessage());
} catch (InvocationTargetException var26) {
logger.error(var26.getMessage());
}
return lst;
}