Skip to content

Instantly share code, notes, and snippets.

Created January 7, 2013 20:26
Show Gist options
  • Save anonymous/4478096 to your computer and use it in GitHub Desktop.
Save anonymous/4478096 to your computer and use it in GitHub Desktop.
Filling out a Java model's attributes in a generic, clean way.
/**
* Generic loadData method. Any parameter that matches a column will
* have data loaded.
* @param resultSet The result set from the database query
* @throws IllegalAccessException The requested field couldn't be accessed
*/
private void loadData(ResultSet resultSet) throws IllegalAccessException {
Field[] fields = getClass().getDeclaredFields();
for (Field f : fields) {
try {
String fieldName = sqlDriver.getDatabaseColumn(f.getName());
f.set(this, resultSet.getObject(fieldName));
} catch (SQLException e) {
// Not a field
}
}
}
/**
* Manipulate string from Camel Case to underscore
* @param fieldName The field name to translate
* @return The translated name
*/
public String getDatabaseColumn(String fieldName) {
return fieldName.replaceAll("([A-Z])", "_$1").toLowerCase();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment