I have been trying to create a robust code that prints out any Java class for debugging. For that, I use reflections. In order to protect against recursive definition such as "Boolean contains static final Boolean TRUE", I ignore fields equal to their parents. I use String += just out of laziness. It doesn't have to be efficient.
Yet, is there a nicer way to do recursive description of objects with reflections?
public String reflectionShowFields(Object parentObject) {
String stringData = "";
for (Field field:parentObject.getClass().getFields()) {
try {
Class<?> type = field.getType();
String typeSimpleName = type.getSimpleName();
Object fieldValue = field.get(parentObject);
String fieldName = field.getName();
if (type.isPrimitive() || type.isEnum() || CharSequence.class.isAssignableFrom(type)) {
stringData += String.format("%s: %s\n", fieldName, fieldValue);
} else if (Iterable.class.isAssignableFrom(type)) {
stringData += String.format(">>> %s[%s]: \n", fieldName, typeSimpleName);
for (Object item:(Iterable)fieldValue) {
stringData += reflectionShowFields(item);
}
stringData += String.format("<<< %s[%s]: \n", fieldName, typeSimpleName);
} else if (!fieldValue.equals(parentObject)) {
stringData += String.format(">>> %s[%s]: %s \n--------\n", fieldName, typeSimpleName, fieldValue.toString());
stringData+= reflectionShowFields(fieldValue);
stringData += String.format("<<< %s[%s]: \n", fieldName, typeSimpleName);
}
} catch (IllegalAccessException ignored) {}
}
return stringData;
}