I did this, but I know, and I strongly feel that this is considered poor programming. I did it because someone forced me, though! (The best solution, I think, would be to write more code ... this was the fastest).
public String getNestedDeclaredField(Object obj, String fieldName) {
if (null == fieldName) {
return null;
}
String[] fieldNames = fieldName.split("\\.");
Field field = null;
Class<? extends Object> requestClass = obj.getClass();
for (String s : fieldNames) {
try
{
field = getSuperClassField(requestClass,
requestClass.getSimpleName(), s);
field.setAccessible(true);
obj = field.get(obj);
if (null == obj) {
return null;
}
requestClass = obj.getClass();
}
catch (Exception e) {
log.error("Error while retrieving field {} from {}", s,
requestClass.toString(), e);
return "";
}
}
return obj.toString();
}
public Field getSuperClassField(Class<? extends Object> clazz,
String clazzName, String fieldName) throws NoSuchFieldException {
Field field = null;
try{
field = clazz.getDeclaredField(fieldName);
}
catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
if (StringUtils.equals(clazz.getSimpleName(), "Object")) {
log.error("Field {} doesn't seem to appear in class {}",
fieldName, clazzName);
throw new NoSuchFieldException();
}
field = getSuperClassField(clazz, clazzName, fieldName);
}
catch (Exception e) {
log.error("Error while retrieving field {} from {}", fieldName,
clazz.toString(), e);
}
return field;
}
Where fieldName (for zipCd): addr.zip.zipCd
It will retrieve the String zipCd value from the Employee object.
source
share