public class AutoRowMapper<T> implements RowMapper<T> {
private static Map<String, Field[]> fields = new HashMap<>();
private Class clazz;
public AutoRowMapper(Class clazz) {
this.clazz = clazz;
}
@Override
public T mapRow(ResultSet rs, int rowNum) {
try {
T t = (T) clazz.newInstance();
Field[] fs = getFields();
for (int i = 0; i < fs.length; i++) {
setValue(t, fs[i], rs.getObject(fs[i].getName()));
}
return t;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
Field[] getFields() {
if (null != fields.get(clazz.getName())) {
return fields.get(clazz.getName());
}
List<Field> list = new ArrayList<>();
Class c = clazz;
while (c != Object.class) {
Field[] declaredFields = c.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
list.add(declaredFields[i]);
}
c = c.getSuperclass();
}
fields.put(clazz.getName(), list.toArray(new Field[list.size()]));
return getFields();
}
void setValue(Object object, Field field, Object value) {
String name = field.getName();
try {
Method method = clazz.getMethod(getMethodName(name), field.getType());
method.invoke(object, value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
String getMethodName(String field) {
return "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
}