hibernate中把查询出来的集合封装为对象集合

public static List objectToList(List obj, Class clazz) throws Exception {
		List list = new ArrayList();
		for (Object result : obj) {
			int i = 0;
			// 获取结果集中每条记录的数据
			Object[] values = (Object[]) result;
			// 通过对象属性进行数据注入
			Field[] f = clazz.getDeclaredFields();
			Object o = clazz.newInstance();
			for (Field field : f) {
				char c = field.getName().charAt(0);
				c -= 32;
				String mname = c + field.getName().substring(1);
				mname = "set" + mname;
				Class<?> type = field.getType();
				Method md = clazz.getMethod(mname, type);
				if (i < values.length) {
					String value = values[i].toString().trim();
						
					if (type == String.class) {
						md.invoke(o, values[i] != null ? value
								: null);

					} else{
						
						if (type == Integer.class) {
							md.invoke(o,Integer.valueOf(value));
	
						} else if (type == Date.class) {
							DateTimeFormat format = (field
									.getAnnotation(DateTimeFormat.class));
							SimpleDateFormat sdf = new SimpleDateFormat(
									format.pattern());
							md.invoke(o,sdf.parse(value) );
	
						} else if (type == BigDecimal.class) {
							md.invoke(o, new BigDecimal(value));
	
						} else if (type == Long.class) {
							md.invoke(o,Long.parseLong(value));
	
						} else if (type == Short.class) {
							md.invoke(o,Short.parseShort(value));
	
						}
					}
				}
				i++;
			}
			list.add(o);
		}
		return list;
	}

展开阅读全文

没有更多推荐了,返回首页