Skip to content

Instantly share code, notes, and snippets.

@bluerogue
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluerogue/8c26722202bdd6cf0b2d to your computer and use it in GitHub Desktop.
Save bluerogue/8c26722202bdd6cf0b2d to your computer and use it in GitHub Desktop.
Reflection method for getting field values in a child class from a parent class
/**
* Assembles a hashmap, omitting null or empty values at runtime. This
* can be used in an abstract class and properly accessed in a child class.
*
* @return returns a hashmap of the current class fields that are not null
*/
public Map<String, String> getNonNullMap() {
Class<?> clazz = null;
Map<String, String> classMap = new HashMap<String, String>();
try {
clazz = Class.forName(this.getClass().getName());
} catch (ClassNotFoundException e) {
LOGGER.error("", e);
}
Field[] classFields = clazz.getDeclaredFields();
for (int i = 0; i < classFields.length; i++) {
Field field = classFields[i];
field.setAccessible(true);
try {
String value = String.valueOf(field.get(this));
if (value != null && !"null".equals(value)
&& !value.isEmpty()
&& !field.getName().equals("serialVersionUID")) {
classMap.put(field.getName(), String.valueOf(field.get(this)));
}
} catch (IllegalArgumentException e) {
LOGGER.error("", e);
} catch (IllegalAccessException e) {
LOGGER.error("", e);
}
field.setAccessible(false);
}
return classMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment