Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Library to print all public fields of nested Java objects?

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?

like image 655
dokondr Avatar asked Oct 17 '25 02:10

dokondr


1 Answers

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);
      }
    }
}
  • We find all we need in the reflection API
  • We need recursion to walk down the object tree
  • We need some special handling for primitives
  • We want some special handling for immutable types (e.g. we don't want to recurse into a String object
  • We need to take care if we visit an object twice.

Note - the code is pretty ugly, hope, it's enough to give you an idea

like image 174
Andreas Dolk Avatar answered Oct 18 '25 16:10

Andreas Dolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!