通过反射从数据库返回集合ResultSet中得到实体对象的list集合

时间:2020-11-29 11:56:59


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangdapeng 
 * @version 1.0
 * @since 1.0
 */
public class DBResultSetReflectionUtil {
	public static List obtainEntityObject(ResultSet rs, Class cls) throws Exception {
		List list = new ArrayList<>();

		Field[] fields = cls.getDeclaredFields();
		while (rs.next()) {
			Object obj = newInstance(cls);
			for (int i = 0; i < fields.length; i++) {
				Class<?> type = fields[i].getType();
				String fieldName = fields[i].getName();

				if (type.getName().equals(String.class.getName())) {
					String value = rs.getString(fields[i].getName());
					setProperty(obj, fieldName, value);
				}
			}
			list.add(obj);
		}
		return list;

	}

	private static Object newInstance(Class<?> cls) throws Exception {
		return cls.newInstance();
	}

	private static void setProperty(Object obj, String name, Object value) throws Exception {
		Class<? extends Object> clazz = obj.getClass();
		String methodName = returnSetMethodName(name);
		Method[] ms = clazz.getMethods();
		for (Method m : ms) {
			if (m.getName().equals(methodName)) {
				if (m.getParameterTypes().length == 1) {
					Class<?> clazzParameterType = m.getParameterTypes()[0];
					setFieldValue(clazzParameterType.getName(), value, m, obj);
					break;
				}
			}
		}
	}

	private static void setFieldValue(String parameterTypeName, Object value, Method m, Object obj) throws Exception {
		if (parameterTypeName.equals(int.class.getName())) {
			value = new Integer(Integer.parseInt(value.toString()));
			m.invoke(obj, value);
			return;
		}
		if (parameterTypeName.equals(String.class.getName())) {
			m.invoke(obj, value);
			return;
		}
	}

	private static String returnSetMethodName(String name) {
		name = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
		return "set" + name;
	}	
}


参考:

http://blog.csdn.net/philosophyatmath/article/details/40710627