public static < T > T cloneObjectWithParents ( T t ) throws IllegalAccessException , InstantiationException { T clone = ( T ) t . getClass ( ) . newInstance ( ) ; List < Field > allFields = new ArrayList <> ( ) ; Class parentClass = t . getClass ( ) . getSuperclass ( ) ; while ( parentClass != null ) { Collections . addAll ( allFields , parentClass . getDeclaredFields ( ) ) ; parentClass = parentClass . getSuperclass ( ) ; } Collections . addAll ( allFields , t . getClass ( ) . getDeclaredFields ( ) ) ; for ( Field field : allFields ) { int modifiers = field . getModifiers ( ) ; //We skip final and static fields if ( ( Modifier . FINAL & modifiers ) != 0 || ( Modifier . STATIC & modifiers ) != 0 ) { continue ; } field . setAccessible ( true ) ; Object value = field . get ( t ) ; if ( Collection . class . isAssignableFrom ( field . getType ( ) ) ) { Collection collection = ( Collection ) field . get ( clone ) ; if ( collection == null ) { collection = ( Collection ) field . get ( t ) . getClass ( ) . newInstance ( ) ; } collection . addAll ( ( Collection ) field . get ( t ) ) ; value = collection ; } else if ( Map . class . isAssignableFrom ( field . getType ( ) ) ) { Map clonMap = ( Map ) field . get ( t ) . getClass ( ) . newInstance ( ) ; clonMap . putAll ( ( Map ) field . get ( t ) ) ; value = clonMap ; } field . set ( clone , value ) ; } return clone ; }
Returns an instance clone . this method gets every class property by reflection including its parents properties