Is there a common Java method to trim every string in an object graph?

Peter Smith picture Peter Smith · Feb 19, 2014 · Viewed 12.4k times · Source

I'm hoping to trim all Strings that are part of an object graph.

So I have an object graph like so

 RootElement
   - name (String)
   - adjective (String)
   - items ArrayOfItems
     - getItems (List<Item>)
       - get(i) (Item)
       Item
         - name (String)
         - value (double)
         - alias (String)
         - references ArrayOfReferences
           - getReferences (List<Reference>)
             - get(i) (Reference)
             Reference
               - prop1 (String)
               - prop2 (Integer)
               - prop3 (String)

There is a get and set pair for every property of every class represented in this object graph. Ideally every field of type String would end up trimmed, including enumerating any child objects contained in collections. There are no cycles contained within the object graph.

Is there any java library that implements some sort of generic object graph visitor pattern or String\Reflection utility library that does this?

An external third party library that does this would also be fine, it does not have to be part of the standard java libraries.

Answer

No, there's no built-in traversal for something like this, and remember that Java Strings are immutable, so you can't actually trim in place--you have to trim and replace. Some objects may not permit modification of their String variables.