public void capture ( ) { // Get the class of the object to build a memento for. Class cls = ob . getClass ( ) ; // Iterate through the classes whole inheritence chain. while ( ! cls . equals ( Object . class ) ) { // Get the classes fields. Field [ ] attrs = cls . getDeclaredFields ( ) ; // Build a new map to put the fields in for the current class. HashMap map = new HashMap ( ) ; // Cache the field values by the class name. values . put ( cls , map ) ; // Loop over all the fields in the current class. for ( Field attr : attrs ) { // Make the field accessible (it may be protected or private). attr . setAccessible ( true ) ; // Check that the field should be captured. if ( shouldBeSaved ( attr ) ) { // Use a try block as access to the field may fail, although this should not happen because // even private, protected and package fields have been made accessible. try { // Cache the field by its name. map . put ( attr . getName ( ) , attr . get ( ob ) ) ; } catch ( IllegalAccessException e ) { // The field could not be accessed but all fields have been made accessible so this should // not happen. throw new IllegalStateException ( "Field '" + attr . getName ( ) + "' could not be accessed but the 'setAccessible(true)' method was invoked on it." , e ) ; } } } // Get the superclass for the next step of the iteration over the whole inheritence chain. cls = cls . getSuperclass ( ) ; } }
Captures an objects state in this memento .