public static void clean ( Object func , boolean checkSerializable ) { if ( func == null ) { return ; } final Class < ? > cls = func . getClass ( ) ; // First find the field name of the "this$0" field, this can // be "this$x" depending on the nesting boolean closureAccessed = false ; for ( Field f : cls . getDeclaredFields ( ) ) { if ( f . getName ( ) . startsWith ( "this$" ) ) { // found a closure referencing field - now try to clean closureAccessed |= cleanThis0 ( func , cls , f . getName ( ) ) ; } } if ( checkSerializable ) { try { InstantiationUtil . serializeObject ( func ) ; } catch ( Exception e ) { String functionType = getSuperClassOrInterfaceName ( func . getClass ( ) ) ; String msg = functionType == null ? ( func + " is not serializable." ) : ( "The implementation of the " + functionType + " is not serializable." ) ; if ( closureAccessed ) { msg += " The implementation accesses fields of its enclosing class, which is " + "a common reason for non-serializability. " + "A common solution is to make the function a proper (non-inner) class, or " + "a static inner class." ; } else { msg += " The object probably contains or references non serializable fields." ; } throw new InvalidProgramException ( msg , e ) ; } } }
Tries to clean the closure of the given object if the object is a non - static inner class .