private static int deepInstanceSize ( Class < ? > clazz ) { if ( clazz . isArray ( ) ) { throw new IllegalArgumentException ( format ( "Cannot determine size of %s because it contains an array" , clazz . getSimpleName ( ) ) ) ; } if ( clazz . isInterface ( ) ) { throw new IllegalArgumentException ( format ( "%s is an interface" , clazz . getSimpleName ( ) ) ) ; } if ( Modifier . isAbstract ( clazz . getModifiers ( ) ) ) { throw new IllegalArgumentException ( format ( "%s is abstract" , clazz . getSimpleName ( ) ) ) ; } if ( ! clazz . getSuperclass ( ) . equals ( Object . class ) ) { throw new IllegalArgumentException ( format ( "Cannot determine size of a subclass. %s extends from %s" , clazz . getSimpleName ( ) , clazz . getSuperclass ( ) . getSimpleName ( ) ) ) ; } int size = ClassLayout . parseClass ( clazz ) . instanceSize ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) { if ( ! field . getType ( ) . isPrimitive ( ) ) { size += deepInstanceSize ( field . getType ( ) ) ; } } return size ; }
Computes the size of an instance of this class assuming that all reference fields are non - null