View Javadoc

1   package com.github.sfleiter.cdi_interceptors.impl;
2   
3   import java.util.Collection;
4   import java.util.Iterator;
5   
6   /**
7    * Helper class to transform objects to a string representation. Supports null,
8    * primitive types, objects, collections and arrays of any kind. Collections and
9    * arrays are transformed recursively. For objects their respective toString
10   * method is used.
11   * 
12   * @author Stefan Fleiter
13   */
14  public class StringTransformer {
15  
16      /**
17       * Transforms any kind of object to a string representation.
18       * 
19       * @param sb
20       *            StringBuilder to which the string representation is appended
21       * @param o
22       *            the object to transform
23       * @param maximumCount
24       *            the maximum number of items in a single collection or array
25       *            instance that are transformed, through the recursive nature
26       *            the aggregated number of transformed items per call is not
27       *            limited
28       */
29      @SuppressWarnings("rawtypes")
30      public void transform(final StringBuilder sb, final Object o, final int maximumCount) {
31          Iterator iterator;
32          int size = 0;
33          if (o == null) {
34              sb.append("null");
35              return;
36          } else if (o instanceof Collection) {
37              Collection c = (Collection) o;
38              size = c.size();
39              iterator = c.iterator();
40              // fall through
41          } else if (o.getClass().isArray()) {
42              ArrayIterator arrayIterator = new ArrayIterator(o);
43              iterator = arrayIterator;
44              size = arrayIterator.getLength();
45              // fall through
46          } else {
47              // no array or collection
48              sb.append(o.toString());
49              return;
50          }
51  
52          // array or collection
53          sb.append("Collection[size=").append(size).append(", ");
54          int i = 0;
55          while (i < maximumCount && iterator.hasNext()) {
56              Object elem = iterator.next();
57              transform(sb, elem, maximumCount);
58              i++;
59              if (iterator.hasNext()) {
60                  sb.append(", ");
61                  if (i == maximumCount) {
62                      sb.append("...");
63                  }
64              }
65          }
66          sb.append("]");
67      }
68  
69  }