Is There a Common Java Method to Trim Every String in an Object Graph?

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.

3

4 Answers

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.

Below is the explanation of solution that I have built using Java Reflection API. I have posted the working code (with its url to github) below. This solution mainly uses:

  1. Java Reflection API
  2. Independent handling of Java Collections
  3. Recursion

To start with, I have used Introspector to go over the readMethods of the Class omitting the methods defined for Object

for (PropertyDescriptor propertyDescriptor : Introspector
                    .getBeanInfo(c, Object.class).getPropertyDescriptors()) {
            Method method = propertyDescriptor.getReadMethod();

Cases

  1. If the current level of Property is of type String
  2. If its an Object Array of Properties
  3. If its a String array
  4. If its a type of Java Collection class
  5. Separate placement for Map with special conditions to process its keys and values

This utility uses the Java Reflection API to traverse through an object graph with disciplined syntax of getters and setters and trims all strings encountered within an Object graph recursively.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.