I need to print all public fields of nested Java objects. These objects only contain data, no methods. On any level of object tree (except leaf nodes) fields may be Maps, Lists, Sets and arrays. Leaf nodes are primitive types. Nested field should be printed as a string of the following format:
<fieldName1>.<fieldName2>. ... <fieldNameN>==<value>
where:
<fieldName1> -- root (top level) field name
<fieldNameN> -- N-level field name
<value> -- N-level field value.
Any library out there to solve this task?
The following example is far from being complete - it drafts a solution and shows some pitfalls:
public class Main {
private static Set<Object> visited = new HashSet<Object>();
public String s = "abc";
public int i = 10;
public Main INSTANCE = this;
public static void main (String[] args) throws Exception
{
printFields(new Main(), "");
}
private static void printFields(Object obj, String pre) throws Exception{
Field[] fields = obj.getClass().getFields();
for (Field field:fields) {
String value = "";
String type = field.getType().toString();
// handle primitve values
if (type.equals("int")) {
value += field.getInt(obj);
}
// handle special types, you may add Wrapper classes
else if (type.equals("class java.lang.String")) {
value = field.get(obj).toString();
}
// handle all object that you want to inspect
else {
if (visited.contains(field.get(obj))) {
// necessary to prevent stack overflow
value = "CYCLE DETECTED";
} else {
// recursing deeper
visited.add(field.get(obj));
pre += field.getName() + ".";
printFields(field.get(obj), pre);
}
}
System.out.printf("%s%s = %s%n", pre, field.getName(), value);
}
}
}
String
objectNote - the code is pretty ugly, hope, it's enough to give you an idea
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With