Last active
August 29, 2015 14:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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