title: How to find Object's size (including contained objects)
body: <p>I want to estimate the size taken up by an object.
  To get the object's size I can just use </p>
  
  <p>To do so I might use <code>Instrumentation.getObjectSize(myObject)</code>, but this will give me a "shallow" size. I want to get the size of the Object, including the sizes of the objects it references.</p>
  
  <p>My thought is that I need to get the size of the object, then go through all the object's fields that are not static or primitives and get the size for the objects that they point to and do this recursively.</p>
  
  <p>Of course, I don't want to count an object size a few times, or get stuck in a loop, So I'll have to remember the objects which size we already counted.</p>
  
  <p>Is there a faster, or a more standard, way to do this?</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>public static long getObjectSize(Object obj)
  {
      return getObjectSize(obj, new HashSet&lt;Object&gt;());
  }
  
  private static long getObjectSize(Object obj, Set&lt;Object&gt; encountered)
  {
      if (encountered.contains(obj))
      {
          // if this object was already counted - don't count it again
          return 0;
      }
      else
      {
          // remember to not count this object's size again
          encountered.add(obj);
      }
      java.lang.reflect.Field fields[] = obj.getClass().getFields();
      long size = Instrumentation.getObjectSize(obj);
      // itereate through all fields               
      for (Field field : fields)
      {
          Class fieldType = field.getType();
          // only if the field isn't a primitive
           if (fieldType != Boolean.class &amp;&amp;
               fieldType != Integer.class &amp;&amp;
               fieldType != Long.class &amp;&amp;
               fieldType != Float.class &amp;&amp;
               fieldType != Character.class &amp;&amp;
               fieldType != Short.class &amp;&amp;
               fieldType != Double.class)
           {
               // get the field's value
               try
               {
                   Object fieldValue = field.get(obj);
                   size += getObjectSize(obj, encountered);
               } 
               catch (IllegalAccessException e) {}
           }
      }
      return size;
  }
  </code></pre>