signature:
public class IteratingBufferedRunningLengthWord32 { /** * Write out up to max words ( negated ) , returns how many were written
 * @ param container target for writes
 * @ param max maximal number of writes
 * @ return how many written */
public int dischargeNegated ( BitmapStorage32 container , int max ) { } }

implementation:
int index = 0 ; while ( ( index < max ) && ( size ( ) > 0 ) ) { // first run
int pl = getRunningLength ( ) ; if ( index + pl > max ) { pl = max - index ; } container . addStreamOfEmptyWords ( ! getRunningBit ( ) , pl ) ; index += pl ; int pd = getNumberOfLiteralWords ( ) ; if ( pd + index > max ) { pd = max - index ; } writeNegatedLiteralWords ( pd , container ) ; discardFirstWords ( pl + pd ) ; index += pd ; } return index ;


signature:
public class IteratingBufferedRunningLengthWord32 { /** * Move to the next RunningLengthWord
 * @ return whether the move was possible */
@ Override public boolean next ( ) { } }

implementation:
if ( ! this . iterator . hasNext ( ) ) { this . brlw . NumberOfLiteralWords = 0 ; this . brlw . RunningLength = 0 ; return false ; } this . brlw . reset ( this . iterator . next ( ) ) ; this . literalWordStartPosition = this . iterator . literalWords ( ) ; // this . brlw . literalWordOffset
return true ;


signature:
public class IteratingBufferedRunningLengthWord32 { /** * Write out the remain words , transforming them to zeroes .
 * @ param container target for writes */
public void dischargeAsEmpty ( BitmapStorage32 container ) { } }

implementation: while ( size ( ) > 0 ) { container . addStreamOfEmptyWords ( false , size ( ) ) ; discardFirstWords ( size ( ) ) ; }


signature:
public class IteratingBufferedRunningLengthWord32 { /** * Write out the remaining words
 * @ param container target for writes */
public void discharge ( BitmapStorage32 container ) { } }

implementation:
// fix the offset
this . brlw . literalWordOffset = this . literalWordStartPosition - this . iterator . literalWords ( ) ; discharge ( this . brlw , this . iterator , container ) ;


signature:
public class IteratingBufferedRunningLengthWord32 { /** * For internal use . ( One could use the non - static discharge method
 * instead , but we expect them to be slower . )
 * @ param initialWord the initial word
 * @ param iterator the iterator
 * @ param container the container */
protected static void discharge ( final BufferedRunningLengthWord32 initialWord , final EWAHIterator32 iterator , final BitmapStorage32 container ) { } }

implementation: BufferedRunningLengthWord32 runningLengthWord = initialWord ; for ( ; ; ) { final int runningLength = runningLengthWord . getRunningLength ( ) ; container . addStreamOfEmptyWords ( runningLengthWord . getRunningBit ( ) , runningLength ) ; container . addStreamOfLiteralWords ( iterator . buffer ( ) , iterator . literalWords ( ) + runningLengthWord . literalWordOffset , runningLengthWord . getNumberOfLiteralWords ( ) ) ; if ( ! iterator . hasNext ( ) ) break ; runningLengthWord = new BufferedRunningLengthWord32 ( iterator . next ( ) ) ; }


signature:
public class BufferedRunningLengthWord32 { /** * Discard first words .
 * @ param x the number of words to be discarded */
public void discardFirstWords ( int x ) { } }

implementation: if ( this . RunningLength >= x ) { this . RunningLength -= x ; return ; } x -= this . RunningLength ; this . RunningLength = 0 ; this . literalWordOffset += x ; this . NumberOfLiteralWords -= x ;


signature:
public class BufferedRunningLengthWord32 { /** * Reset the values using the provided word .
 * @ param a the word */
public void reset ( final int a ) { } }

implementation: this . NumberOfLiteralWords = ( a >>> ( 1 + RunningLengthWord32 . RUNNING_LENGTH_BITS ) ) ; this . RunningBit = ( a & 1 ) != 0 ; this . RunningLength = ( ( a >>> 1 ) & RunningLengthWord32 . LARGEST_RUNNING_LENGTH_COUNT ) ; this . literalWordOffset = 0 ;


signature:
public class EWAHPointer32 { /** * Process the next run */
public void parseNextRun ( ) { } }

implementation:
if ( ( this . isLiteral ) || ( this . iterator . getNumberOfLiteralWords ( ) == 0 ) ) { // no choice , must load next runs
this . iterator . discardFirstWords ( this . iterator . size ( ) ) ; if ( this . iterator . getRunningLength ( ) > 0 ) { this . endrun += this . iterator . getRunningLength ( ) ; this . isLiteral = false ; this . value = this . iterator . getRunningBit ( ) ; } else if ( this . iterator . getNumberOfLiteralWords ( ) > 0 ) { this . isLiteral = true ; this . endrun += this . iterator . getNumberOfLiteralWords ( ) ; } else { this . dead = true ; } } else { this . isLiteral = true ; this . endrun += this . iterator . getNumberOfLiteralWords ( ) ; }


signature:
public class TapBarMenu { /** * Open the menu . */
public void open ( ) { } }

implementation: state = State . OPENED ; showIcons ( true ) ; animator [ LEFT ] . setFloatValues ( button [ LEFT ] , 0 ) ; animator [ RIGHT ] . setFloatValues ( button [ RIGHT ] , width ) ; animator [ RADIUS ] . setFloatValues ( button [ RADIUS ] , 0 ) ; animator [ TOP ] . setFloatValues ( button [ TOP ] , 0 ) ; animator [ BOTTOM ] . setFloatValues ( button [ BOTTOM ] , height ) ; animatorSet . cancel ( ) ; animatorSet . start ( ) ; if ( iconOpenedDrawable instanceof Animatable ) { ( ( Animatable ) iconOpenedDrawable ) . start ( ) ; } ViewGroup parentView = ( ViewGroup ) TapBarMenu . this . getParent ( ) ; this . animate ( ) . y ( menuAnchor == MENU_ANCHOR_BOTTOM ? parentView . getBottom ( ) - height : 0 ) . setDuration ( animationDuration ) . setInterpolator ( DECELERATE_INTERPOLATOR ) . start ( ) ;


signature:
public class TapBarMenu { /** * Close the menu . */
public void close ( ) { } }

implementation: updateDimensions ( width , height ) ; state = State . CLOSED ; showIcons ( false ) ; animator [ LEFT ] . setFloatValues ( 0 , button [ LEFT ] ) ; animator [ RIGHT ] . setFloatValues ( width , button [ RIGHT ] ) ; animator [ RADIUS ] . setFloatValues ( 0 , button [ RADIUS ] ) ; animator [ TOP ] . setFloatValues ( 0 , button [ TOP ] ) ; animator [ BOTTOM ] . setFloatValues ( height , button [ BOTTOM ] ) ; animatorSet . cancel ( ) ; animatorSet . start ( ) ; if ( iconClosedDrawable instanceof Animatable ) { ( ( Animatable ) iconClosedDrawable ) . start ( ) ; } this . animate ( ) . y ( yPosition ) . setDuration ( animationDuration ) . setInterpolator ( DECELERATE_INTERPOLATOR ) . start ( ) ;


signature:
public class TapBarMenu { /** * Sets TapBarMenu ' s background color from given resource .
 * @ param colorResId Color resource id . For example : R . color . holo _ blue _ light */
public void setMenuBackgroundColor ( int colorResId ) { } }

implementation: backgroundColor = ContextCompat . getColor ( getContext ( ) , colorResId ) ; paint . setColor ( backgroundColor ) ; invalidate ( ) ;


signature:
public class PorterStemmer { /** * step1 ( ) gets rid of plurals and - ed or - ing . e . g .
 * caresses - > caress ponies - > poni ties - > ti caress - > caress cats - > cat
 * feed - > feed agreed - > agree disabled - > disable
 * matting - > mat mating - > mate meeting - > meet milling - > mill messing - >
 * mess
 * meetings - > meet */
private void step1 ( ) { } }

implementation: if ( b [ k ] == 's' ) { if ( ends ( "sses" ) ) k -= 2 ; else if ( ends ( "ies" ) ) setto ( "i" ) ; else if ( b [ k - 1 ] != 's' ) k -- ; } if ( ends ( "eed" ) ) { if ( m ( ) > 0 ) k -- ; } else if ( ( ends ( "ed" ) || ends ( "ing" ) ) && vowelinstem ( ) ) { k = j ; if ( ends ( "at" ) ) setto ( "ate" ) ; else if ( ends ( "bl" ) ) setto ( "ble" ) ; else if ( ends ( "iz" ) ) setto ( "ize" ) ; else if ( doublec ( k ) ) { int ch = b [ k -- ] ; if ( ch == 'l' || ch == 's' || ch == 'z' ) k ++ ; } else if ( m ( ) == 1 && cvc ( k ) ) setto ( "e" ) ; }


signature:
public class PorterStemmer { /** * step3 ( ) maps double suffices to single ones . so - ization ( = - ize plus
 * - ation ) maps to - ize etc . note that the string before the suffix must
 * give m ( ) > 0. */
private void step3 ( ) { } }

implementation:
if ( k == k0 ) return ; /* For Bug 1 */
switch ( b [ k - 1 ] ) { case 'a' : if ( ends ( "ational" ) ) { r ( "ate" ) ; break ; } if ( ends ( "tional" ) ) { r ( "tion" ) ; break ; } break ; case 'c' : if ( ends ( "enci" ) ) { r ( "ence" ) ; break ; } if ( ends ( "anci" ) ) { r ( "ance" ) ; break ; } break ; case 'e' : if ( ends ( "izer" ) ) { r ( "ize" ) ; break ; } break ; case 'l' : if ( ends ( "bli" ) ) { r ( "ble" ) ; break ; } if ( ends ( "alli" ) ) { r ( "al" ) ; break ; } if ( ends ( "entli" ) ) { r ( "ent" ) ; break ; } if ( ends ( "eli" ) ) { r ( "e" ) ; break ; } if ( ends ( "ousli" ) ) { r ( "ous" ) ; break ; } break ; case 'o' : if ( ends ( "ization" ) ) { r ( "ize" ) ; break ; } if ( ends ( "ation" ) ) { r ( "ate" ) ; break ; } if ( ends ( "ator" ) ) { r ( "ate" ) ; break ; } break ; case 's' : if ( ends ( "alism" ) ) { r ( "al" ) ; break ; } if ( ends ( "iveness" ) ) { r ( "ive" ) ; break ; } if ( ends ( "fulness" ) ) { r ( "ful" ) ; break ; } if ( ends ( "ousness" ) ) { r ( "ous" ) ; break ; } break ; case 't' : if ( ends ( "aliti" ) ) { r ( "al" ) ; break ; } if ( ends ( "iviti" ) ) { r ( "ive" ) ; break ; } if ( ends ( "biliti" ) ) { r ( "ble" ) ; break ; } break ; case 'g' : if ( ends ( "logi" ) ) { r ( "log" ) ; break ; } }


signature:
public class PorterStemmer { /** * / * step5 ( ) takes off - ant , - ence etc . , in context < c > vcvc < v > . */
private void step5 ( ) { } }

implementation:
if ( k == k0 ) return ; /* for Bug 1 */
switch ( b [ k - 1 ] ) { case 'a' : if ( ends ( "al" ) ) break ; return ; case 'c' : if ( ends ( "ance" ) ) break ; if ( ends ( "ence" ) ) break ; return ; case 'e' : if ( ends ( "er" ) ) break ; return ; case 'i' : if ( ends ( "ic" ) ) break ; return ; case 'l' : if ( ends ( "able" ) ) break ; if ( ends ( "ible" ) ) break ; return ; case 'n' : if ( ends ( "ant" ) ) break ; if ( ends ( "ement" ) ) break ; if ( ends ( "ment" ) ) break ; /* element etc . not stripped before the m */
if ( ends ( "ent" ) ) break ; return ; case 'o' : if ( ends ( "ion" ) && j >= 0 && ( b [ j ] == 's' || b [ j ] == 't' ) ) break ; /* j > = 0 fixes Bug 2 */
if ( ends ( "ou" ) ) break ; return ; /* takes care of - ous */
case 's' : if ( ends ( "ism" ) ) break ; return ; case 't' : if ( ends ( "ate" ) ) break ; if ( ends ( "iti" ) ) break ; return ; case 'u' : if ( ends ( "ous" ) ) break ; return ; case 'v' : if ( ends ( "ive" ) ) break ; return ; case 'z' : if ( ends ( "ize" ) ) break ; return ; default : return ; } if ( m ( ) > 1 ) k = j ;


signature:
public class HanLPAnalyzer { /** * 重载Analyzer接口 , 构造分词组件 */
@ Override protected TokenStreamComponents createComponents ( String fieldName ) { } }

implementation: Tokenizer tokenizer = new HanLPTokenizer ( HanLP . newSegment ( ) . enableOffset ( true ) , filter , enablePorterStemming ) ; return new TokenStreamComponents ( tokenizer ) ;


signature:
public class H2URLParser { /** * Fetch range index that the database name from connection url if H2 database running with file
 * mode .
 * @ return range index that the database name . */
private int [ ] fetchDatabaseNameRangeIndexFromURLForH2FileMode ( String url ) { } }

implementation: int fileLabelIndex = url . indexOf ( FILE_MODE_FLAG ) ; int parameterLabelIndex = url . indexOf ( ";" , fileLabelIndex ) ; if ( parameterLabelIndex == - 1 ) { parameterLabelIndex = url . length ( ) ; } if ( fileLabelIndex != - 1 ) { return new int [ ] { fileLabelIndex + FILE_MODE_FLAG . length ( ) + 1 , parameterLabelIndex } ; } else { return null ; }


signature:
public class H2URLParser { /** * Fetch range index that the database name from connection url if H2 database running with memory
 * mode .
 * @ return range index that the database name . */
private int [ ] fetchDatabaseNameRangeIndexFromURLForH2MemMode ( String url ) { } }

implementation: int fileLabelIndex = url . indexOf ( MEMORY_MODE_FLAG ) ; int parameterLabelIndex = url . indexOf ( ";" , fileLabelIndex ) ; if ( parameterLabelIndex == - 1 ) { parameterLabelIndex = url . length ( ) ; } if ( fileLabelIndex != - 1 ) { return new int [ ] { fileLabelIndex + MEMORY_MODE_FLAG . length ( ) + 1 , parameterLabelIndex } ; } else { return null ; }


signature:
public class URLParser { /** * parse the url to the ConnectionInfo */
public static ConnectionInfo parser ( String url ) { } }

implementation: if ( null == url ) { return ConnectionInfo . UNKNOWN_CONNECTION_INFO ; } String lowerCaseUrl = url . toLowerCase ( ) ; ConnectionURLParser parser = findURLParser ( lowerCaseUrl ) ; if ( parser == null ) { return ConnectionInfo . UNKNOWN_CONNECTION_INFO ; } try { return parser . parse ( url ) ; } catch ( Exception e ) { log . log ( Level . WARNING , "error occurs when paring jdbc url" ) ; } return ConnectionInfo . UNKNOWN_CONNECTION_INFO ;


signature:
public class URLParser { /** * register new ConnectionURLParser . Can override existing parser . */
public static void registerConnectionParser ( String urlPrefix , ConnectionURLParser parser ) { } }

implementation: if ( null == urlPrefix || parser == null ) { throw new IllegalArgumentException ( "urlPrefix and parser can not be null" ) ; } parserRegister . put ( urlPrefix . toLowerCase ( ) , parser ) ;


signature:
public class AbstractURLParser { /** * Fetch database host ( s ) from connection url .
 * @ return database host ( s ) . */
protected String fetchDatabaseHostsFromURL ( String url ) { } }

implementation: URLLocation hostsLocation = fetchDatabaseHostsIndexRange ( url ) ; return url . substring ( hostsLocation . startIndex ( ) , hostsLocation . endIndex ( ) ) ;


signature:
public class AbstractURLParser { /** * Fetch database name from connection url .
 * @ return database name . */
protected String fetchDatabaseNameFromURL ( String url ) { } }

implementation: URLLocation hostsLocation = fetchDatabaseNameIndexRange ( url ) ; return url . substring ( hostsLocation . startIndex ( ) , hostsLocation . endIndex ( ) ) ;


signature:
public class Daemon { /** * start daemon */
private static void start ( Context context , Class < ? > daemonClazzName , int interval ) { } }

implementation:
String cmd = context . getDir ( BIN_DIR_NAME , Context . MODE_PRIVATE ) . getAbsolutePath ( ) + File . separator + DAEMON_BIN_NAME ; /* create the command string */
StringBuilder cmdBuilder = new StringBuilder ( ) ; cmdBuilder . append ( cmd ) ; cmdBuilder . append ( " -p " ) ; cmdBuilder . append ( context . getPackageName ( ) ) ; cmdBuilder . append ( " -s " ) ; cmdBuilder . append ( daemonClazzName . getName ( ) ) ; cmdBuilder . append ( " -t " ) ; cmdBuilder . append ( interval ) ; try { Runtime . getRuntime ( ) . exec ( cmdBuilder . toString ( ) ) . waitFor ( ) ; } catch ( IOException | InterruptedException e ) { Log . e ( TAG , "start daemon error: " + e . getMessage ( ) ) ; }


signature:
public class Daemon { /** * Run daemon process .
 * @ param context context
 * @ param daemonServiceClazz the name of daemon service class
 * @ param interval the interval to check */
public static void run ( final Context context , final Class < ? > daemonServiceClazz , final int interval ) { } }

implementation: new Thread ( new Runnable ( ) { @ Override public void run ( ) { Command . install ( context , BIN_DIR_NAME , DAEMON_BIN_NAME ) ; start ( context , daemonServiceClazz , interval ) ; } } ) . start ( ) ;


signature:
public class Command { /** * copy file to destination */
private static void copyFile ( File file , InputStream is , String mode ) throws IOException , InterruptedException { } }

implementation: final String abspath = file . getAbsolutePath ( ) ; final FileOutputStream out = new FileOutputStream ( file ) ; byte buf [ ] = new byte [ 1024 ] ; int len ; while ( ( len = is . read ( buf ) ) > 0 ) { out . write ( buf , 0 , len ) ; } out . close ( ) ; is . close ( ) ; Runtime . getRuntime ( ) . exec ( "chmod " + mode + " " + abspath ) . waitFor ( ) ;


signature:
public class Command { /** * copy file in assets into destination file
 * @ param context context
 * @ param assetsFilename file name in assets
 * @ param file the file to copy to
 * @ param mode mode of file
 * @ throws IOException
 * @ throws InterruptedException */
public static void copyAssets ( Context context , String assetsFilename , File file , String mode ) throws IOException , InterruptedException { } }

implementation: AssetManager manager = context . getAssets ( ) ; final InputStream is = manager . open ( assetsFilename ) ; copyFile ( file , is , mode ) ;


signature:
public class Command { /** * Install specified binary into destination directory .
 * @ param context context
 * @ param destDir destionation directory
 * @ param filename filename of binary
 * @ return true if install successfully , otherwise return false */
@ SuppressWarnings ( "deprecation" ) public static boolean install ( Context context , String destDir , String filename ) { } }

implementation:
String binaryDir = "armeabi" ; String abi = Build . CPU_ABI ; if ( abi . startsWith ( "armeabi-v7a" ) ) { binaryDir = "armeabi-v7a" ; } else if ( abi . startsWith ( "x86" ) ) { binaryDir = "x86" ; } /* for different platform */
String assetfilename = binaryDir + File . separator + filename ; try { File f = new File ( context . getDir ( destDir , Context . MODE_PRIVATE ) , filename ) ; if ( f . exists ( ) ) { Log . d ( TAG , "binary has existed" ) ; return false ; } copyAssets ( context , assetfilename , f , "0755" ) ; return true ; } catch ( Exception e ) { Log . e ( TAG , "installBinary failed: " + e . getMessage ( ) ) ; return false ; }


signature:
public class Resolver { /** * Walk a JsonObject ( Map of String keys to values ) and return the
 * Java object equivalent filled in as best as possible ( everything
 * except unresolved reference fields or unresolved array / collection elements ) .
 * @ param root JsonObject reference to a Map - of - Maps representation of the JSON
 * input after it has been completely read .
 * @ return Properly constructed , typed , Java object graph built from a Map
 * of Maps representation ( JsonObject root ) . */
protected Object convertMapsToObjects ( final JsonObject < String , Object > root ) { } }

implementation: final Deque < JsonObject < String , Object > > stack = new ArrayDeque < JsonObject < String , Object > > ( ) ; stack . addFirst ( root ) ; while ( ! stack . isEmpty ( ) ) { final JsonObject < String , Object > jsonObj = stack . removeFirst ( ) ; if ( jsonObj . isArray ( ) ) { traverseArray ( stack , jsonObj ) ; } else if ( jsonObj . isCollection ( ) ) { traverseCollection ( stack , jsonObj ) ; } else if ( jsonObj . isMap ( ) ) { traverseMap ( stack , jsonObj ) ; } else { Object special ; if ( ( special = readIfMatching ( jsonObj , null , stack ) ) != null ) { jsonObj . target = special ; } else { traverseFields ( stack , jsonObj ) ; } } } return root . target ;


signature:
public class Resolver { /** * calls the missing field handler if any for each recorded missing field . */
private void handleMissingFields ( ) { } }

implementation: MissingFieldHandler missingFieldHandler = reader . getMissingFieldHandler ( ) ; if ( missingFieldHandler != null ) { for ( Missingfields mf : missingFields ) { missingFieldHandler . fieldMissing ( mf . target , mf . fieldName , mf . value ) ; } } // else no handler so ignore .


signature:
public class Resolver { /** * Process java . util . Map and it ' s derivatives . These can be written specially
 * so that the serialization would not expose the derivative class internals
 * ( internal fields of TreeMap for example ) .
 * @ param stack a Stack ( Deque ) used to support graph traversal .
 * @ param jsonObj a Map - of - Map representation of the JSON input stream . */
protected void traverseMap ( Deque < JsonObject < String , Object > > stack , JsonObject < String , Object > jsonObj ) { } }

implementation:
// Convert @ keys to a Collection of Java objects .
convertMapToKeysItems ( jsonObj ) ; final Object [ ] keys = ( Object [ ] ) jsonObj . get ( "@keys" ) ; final Object [ ] items = jsonObj . getArray ( ) ; if ( keys == null || items == null ) { if ( keys != items ) { throw new JsonIoException ( "Map written where one of @keys or @items is empty" ) ; } return ; } final int size = keys . length ; if ( size != items . length ) { throw new JsonIoException ( "Map written with @keys and @items entries of different sizes" ) ; } Object [ ] mapKeys = buildCollection ( stack , keys , size ) ; Object [ ] mapValues = buildCollection ( stack , items , size ) ; // Save these for later so that unresolved references inside keys or values
// get patched first , and then build the Maps .
prettyMaps . add ( new Object [ ] { jsonObj , mapKeys , mapValues } ) ;


signature:
public class Resolver { /** * Convert an input JsonObject map ( known to represent a Map . class or derivative ) that has regular keys and values
 * to have its keys placed into @ keys , and its values placed into @ items .
 * @ param map Map to convert */
protected static void convertMapToKeysItems ( final JsonObject < String , Object > map ) { } }

implementation: if ( ! map . containsKey ( "@keys" ) && ! map . isReference ( ) ) { final Object [ ] keys = new Object [ map . size ( ) ] ; final Object [ ] values = new Object [ map . size ( ) ] ; int i = 0 ; for ( Object e : map . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) e ; keys [ i ] = entry . getKey ( ) ; values [ i ] = entry . getValue ( ) ; i ++ ; } String saveType = map . getType ( ) ; map . clear ( ) ; map . setType ( saveType ) ; map . put ( "@keys" , keys ) ; map . put ( "@items" , values ) ; }


signature:
public class Resolver { /** * This method creates a Java Object instance based on the passed in parameters .
 * If the JsonObject contains a key ' @ type ' then that is used , as the type was explicitly
 * set in the JSON stream . If the key ' @ type ' does not exist , then the passed in Class
 * is used to create the instance , handling creating an Array or regular Object
 * instance .
 * < br >
 * The ' @ type ' is not often specified in the JSON input stream , as in many
 * cases it can be inferred from a field reference or array component type .
 * @ param clazz Instance will be create of this class .
 * @ param jsonObj Map - of - Map representation of object to create .
 * @ return a new Java object of the appropriate type ( clazz ) using the jsonObj to provide
 * enough hints to get the right class instantiated . It is not populated when returned . */
protected Object createJavaObjectInstance ( Class clazz , JsonObject jsonObj ) { } }

implementation:
final boolean useMapsLocal = useMaps ; String type = jsonObj . type ; // We can ' t set values to an Object , so well try to use the contained type instead
if ( "java.lang.Object" . equals ( type ) ) { Object value = jsonObj . get ( "value" ) ; if ( jsonObj . keySet ( ) . size ( ) == 1 && value != null ) { type = value . getClass ( ) . getName ( ) ; } } Object mate ; // @ type always takes precedence over inferred Java ( clazz ) type .
if ( type != null ) { // @ type is explicitly set , use that as it always takes precedence
Class c ; try { c = MetaUtils . classForName ( type , reader . getClassLoader ( ) , failOnUnknownType ) ; } catch ( Exception e ) { if ( useMapsLocal ) { jsonObj . type = null ; jsonObj . target = null ; return jsonObj ; } else { String name = clazz == null ? "null" : clazz . getName ( ) ; throw new JsonIoException ( "Unable to create class: " + name , e ) ; } } if ( c . isArray ( ) ) { // Handle [ ]
Object [ ] items = jsonObj . getArray ( ) ; int size = ( items == null ) ? 0 : items . length ; if ( c == char [ ] . class ) { jsonObj . moveCharsToMate ( ) ; mate = jsonObj . target ; } else { mate = Array . newInstance ( c . getComponentType ( ) , size ) ; } } else { // Handle regular field . object reference
if ( MetaUtils . isPrimitive ( c ) ) { mate = MetaUtils . convert ( c , jsonObj . get ( "value" ) ) ; } else if ( c == Class . class ) { mate = MetaUtils . classForName ( ( String ) jsonObj . get ( "value" ) , reader . getClassLoader ( ) ) ; } else if ( c . isEnum ( ) ) { mate = getEnum ( c , jsonObj ) ; } else if ( Enum . class . isAssignableFrom ( c ) ) // anonymous subclass of an enum
{ mate = getEnum ( c . getSuperclass ( ) , jsonObj ) ; } else if ( EnumSet . class . isAssignableFrom ( c ) ) { mate = getEnumSet ( c , jsonObj ) ; } else if ( ( mate = coerceCertainTypes ( c . getName ( ) ) ) != null ) { // if coerceCertainTypes ( ) returns non - null , it did the work
} else { mate = newInstance ( c , jsonObj ) ; } } } else { // @ type , not specified , figure out appropriate type
Object [ ] items = jsonObj . getArray ( ) ; // if @ items is specified , it must be an [ ] type .
// if clazz . isArray ( ) , then it must be an [ ] type .
if ( clazz . isArray ( ) || ( items != null && clazz == Object . class && ! jsonObj . containsKey ( "@keys" ) ) ) { int size = ( items == null ) ? 0 : items . length ; mate = Array . newInstance ( clazz . isArray ( ) ? clazz . getComponentType ( ) : Object . class , size ) ; } else if ( clazz . isEnum ( ) ) { mate = getEnum ( clazz , jsonObj ) ; } else if ( Enum . class . isAssignableFrom ( clazz ) ) // anonymous subclass of an enum
{ mate = getEnum ( clazz . getSuperclass ( ) , jsonObj ) ; } else if ( EnumSet . class . isAssignableFrom ( clazz ) ) // anonymous subclass of an enum
{ mate = getEnumSet ( clazz , jsonObj ) ; } else if ( ( mate = coerceCertainTypes ( clazz . getName ( ) ) ) != null ) { // if coerceCertainTypes ( ) returns non - null , it did the work
} else if ( clazz == Object . class && ! useMapsLocal ) { if ( unknownClass == null ) { mate = new JsonObject ( ) ; ( ( JsonObject ) mate ) . type = Map . class . getName ( ) ; } else if ( unknownClass instanceof String ) { mate = newInstance ( MetaUtils . classForName ( ( ( String ) unknownClass ) . trim ( ) , reader . getClassLoader ( ) ) , jsonObj ) ; } else { throw new JsonIoException ( "Unable to determine object type at column: " + jsonObj . col + ", line: " + jsonObj . line + ", content: " + jsonObj ) ; } } else { mate = newInstance ( clazz , jsonObj ) ; } } jsonObj . target = mate ; return jsonObj . target ;


signature:
public class Resolver { /** * Fetch enum value ( may need to try twice , due to potential ' name ' field shadowing by enum subclasses */
private Object getEnum ( Class c , JsonObject jsonObj ) { } }

implementation:
try { return Enum . valueOf ( c , ( String ) jsonObj . get ( "name" ) ) ; } catch ( Exception e ) { // In case the enum class has it ' s own ' name ' member variable ( shadowing the ' name ' variable on Enum )
return Enum . valueOf ( c , ( String ) jsonObj . get ( "java.lang.Enum.name" ) ) ; }


signature:
public class Resolver { /** * Create the EnumSet with its values ( it must be created this way ) */
private Object getEnumSet ( Class c , JsonObject < String , Object > jsonObj ) { } }

implementation:
Object [ ] items = jsonObj . getArray ( ) ; if ( items == null || items . length == 0 ) { return newInstance ( c , jsonObj ) ; } JsonObject item = ( JsonObject ) items [ 0 ] ; String type = item . getType ( ) ; Class enumClass = MetaUtils . classForName ( type , reader . getClassLoader ( ) ) ; EnumSet enumSet = null ; for ( Object objectItem : items ) { item = ( JsonObject ) objectItem ; Enum enumItem = ( Enum ) getEnum ( enumClass , item ) ; if ( enumSet == null ) { // Lazy init the EnumSet
enumSet = EnumSet . of ( enumItem ) ; } else { enumSet . add ( enumItem ) ; } } return enumSet ;


signature:
public class Resolver { /** * For all fields where the value was " @ ref " : " n " where ' n ' was the id of an object
 * that had not yet been encountered in the stream , make the final substitution . */
protected void patchUnresolvedReferences ( ) { } }

implementation:
Iterator i = unresolvedRefs . iterator ( ) ; while ( i . hasNext ( ) ) { UnresolvedReference ref = ( UnresolvedReference ) i . next ( ) ; Object objToFix = ref . referencingObj . target ; JsonObject objReferenced = reader . getObjectsRead ( ) . get ( ref . refId ) ; if ( ref . index >= 0 ) { // Fix [ ] ' s and Collections containing a forward reference .
if ( objToFix instanceof List ) { // Patch up Indexable Collections
List list = ( List ) objToFix ; list . set ( ref . index , objReferenced . target ) ; } else if ( objToFix instanceof Collection ) { // Add element ( since it was not indexable , add it to collection )
Collection col = ( Collection ) objToFix ; col . add ( objReferenced . target ) ; } else { Array . set ( objToFix , ref . index , objReferenced . target ) ; // patch array element here
} } else { // Fix field forward reference
Field field = MetaUtils . getField ( objToFix . getClass ( ) , ref . field ) ; if ( field != null ) { try { field . set ( objToFix , objReferenced . target ) ; // patch field here
} catch ( Exception e ) { throw new JsonIoException ( "Error setting field while resolving references '" + field . getName ( ) + "', @ref = " + ref . refId , e ) ; } } } i . remove ( ) ; }


signature:
public class Resolver { /** * Process Maps / Sets ( fix up their internal indexing structure )
 * This is required because Maps hash items using hashCode ( ) , which will
 * change between VMs . Rehashing the map fixes this .
 * < br >
 * If useMaps = = true , then move @ keys to keys and @ items to values
 * and then drop these two entries from the map .
 * < br >
 * This hashes both Sets and Maps because the JDK sets are implemented
 * as Maps . If you have a custom built Set , this would not ' treat ' it
 * and you would need to provider a custom reader for that set . */
protected void rehashMaps ( ) { } }

implementation:
final boolean useMapsLocal = useMaps ; for ( Object [ ] mapPieces : prettyMaps ) { JsonObject jObj = ( JsonObject ) mapPieces [ 0 ] ; Object [ ] javaKeys , javaValues ; Map map ; if ( useMapsLocal ) { // Make the @ keys be the actual keys of the map .
map = jObj ; javaKeys = ( Object [ ] ) jObj . remove ( "@keys" ) ; javaValues = ( Object [ ] ) jObj . remove ( "@items" ) ; } else { map = ( Map ) jObj . target ; javaKeys = ( Object [ ] ) mapPieces [ 1 ] ; javaValues = ( Object [ ] ) mapPieces [ 2 ] ; jObj . clear ( ) ; } int j = 0 ; while ( javaKeys != null && j < javaKeys . length ) { map . put ( javaKeys [ j ] , javaValues [ j ] ) ; j ++ ; } }


signature:
public class Readers { /** * = = = = = Maintain dependency knowledge in once place , down here = = = = = */
static Class classForName ( String name , ClassLoader classLoader ) { } }

implementation: return MetaUtils . classForName ( name , classLoader ) ;


signature:
public class MapResolver { /** * Walk the JsonObject fields and perform necessary substitutions so that all references matched up .
 * This code patches @ ref and @ id pairings up , in the ' Map of Map ' mode . Where the JSON may contain
 * an @ id of an object which can have more than one @ ref to it , this code will make sure that each
 * @ ref ( value side of the Map associated to a given field name ) will be pointer to the appropriate Map
 * instance .
 * @ param stack Stack ( Deque ) used for graph traversal .
 * @ param jsonObj a Map - of - Map representation of the current object being examined ( containing all fields ) . */
public void traverseFields ( final Deque < JsonObject < String , Object > > stack , final JsonObject < String , Object > jsonObj ) { } }

implementation:
final Object target = jsonObj . target ; for ( Map . Entry < String , Object > e : jsonObj . entrySet ( ) ) { final String fieldName = e . getKey ( ) ; final Field field = ( target != null ) ? MetaUtils . getField ( target . getClass ( ) , fieldName ) : null ; final Object rhs = e . getValue ( ) ; if ( rhs == null ) { jsonObj . put ( fieldName , null ) ; } else if ( rhs == JsonParser . EMPTY_OBJECT ) { jsonObj . put ( fieldName , new JsonObject ( ) ) ; } else if ( rhs . getClass ( ) . isArray ( ) ) { // RHS is an array
// Trace the contents of the array ( so references inside the array and into the array work )
JsonObject < String , Object > jsonArray = new JsonObject < String , Object > ( ) ; jsonArray . put ( "@items" , rhs ) ; stack . addFirst ( jsonArray ) ; // Assign the array directly to the Map key ( field name )
jsonObj . put ( fieldName , rhs ) ; } else if ( rhs instanceof JsonObject ) { JsonObject < String , Object > jObj = ( JsonObject ) rhs ; if ( field != null && MetaUtils . isLogicalPrimitive ( field . getType ( ) ) ) { jObj . put ( "value" , MetaUtils . convert ( field . getType ( ) , jObj . get ( "value" ) ) ) ; continue ; } Long refId = jObj . getReferenceId ( ) ; if ( refId != null ) { // Correct field references
JsonObject refObject = getReferencedObj ( refId ) ; jsonObj . put ( fieldName , refObject ) ; // Update Map - of - Maps reference
} else { stack . addFirst ( jObj ) ; } } else if ( field != null ) { // The code below is ' upgrading ' the RHS values in the passed in JsonObject Map
// by using the @ type class name ( when specified and exists ) , to coerce the vanilla
// JSON values into the proper types defined by the class listed in @ type . This is
// a cool feature of json - io , that even when reading a map - of - maps JSON file , it will
// improve the final types of values in the maps RHS , to be of the field type that
// was optionally specified in @ type .
final Class fieldType = field . getType ( ) ; if ( MetaUtils . isPrimitive ( fieldType ) || BigDecimal . class . equals ( fieldType ) || BigInteger . class . equals ( fieldType ) || Date . class . equals ( fieldType ) ) { jsonObj . put ( fieldName , MetaUtils . convert ( fieldType , rhs ) ) ; } else if ( rhs instanceof String ) { if ( fieldType != String . class && fieldType != StringBuilder . class && fieldType != StringBuffer . class ) { if ( "" . equals ( ( ( String ) rhs ) . trim ( ) ) ) { // Allow " " to null out a non - String field on the inbound JSON
jsonObj . put ( fieldName , null ) ; } } } } } jsonObj . target = null ; // don ' t waste space ( used for typed return , not for Map return )


signature:
public class MapResolver { /** * Process java . util . Collection and it ' s derivatives . Collections are written specially
 * so that the serialization does not expose the Collection ' s internal structure , for
 * example a TreeSet . All entries are processed , except unresolved references , which
 * are filled in later . For an indexable collection , the unresolved references are set
 * back into the proper element location . For non - indexable collections ( Sets ) , the
 * unresolved references are added via . add ( ) .
 * @ param stack a Stack ( Deque ) used to support graph traversal .
 * @ param jsonObj a Map - of - Map representation of the JSON input stream . */
protected void traverseCollection ( final Deque < JsonObject < String , Object > > stack , final JsonObject < String , Object > jsonObj ) { } }

implementation:
final Object [ ] items = jsonObj . getArray ( ) ; if ( items == null || items . length == 0 ) { return ; } int idx = 0 ; final List copy = new ArrayList ( items . length ) ; for ( Object element : items ) { if ( element == JsonParser . EMPTY_OBJECT ) { copy . add ( new JsonObject ( ) ) ; continue ; } copy . add ( element ) ; if ( element instanceof Object [ ] ) { // array element inside Collection
JsonObject < String , Object > jsonObject = new JsonObject < String , Object > ( ) ; jsonObject . put ( "@items" , element ) ; stack . addFirst ( jsonObject ) ; } else if ( element instanceof JsonObject ) { JsonObject < String , Object > jsonObject = ( JsonObject < String , Object > ) element ; Long refId = jsonObject . getReferenceId ( ) ; if ( refId != null ) { // connect reference
JsonObject refObject = getReferencedObj ( refId ) ; copy . set ( idx , refObject ) ; } else { stack . addFirst ( jsonObject ) ; } } idx ++ ; } jsonObj . target = null ; // don ' t waste space ( used for typed return , not generic Map return )
for ( int i = 0 ; i < items . length ; i ++ ) { items [ i ] = copy . get ( i ) ; }


signature:
public class JsonReader { /** * Convert the passed in JSON string into a Java object graph .
 * @ param json String JSON input
 * @ param optionalArgs Map of optional parameters to control parsing . See readme file for details .
 * @ return Java object graph matching JSON input */
public static Object jsonToJava ( String json , Map < String , Object > optionalArgs ) { } }

implementation: if ( optionalArgs == null ) { optionalArgs = new HashMap < String , Object > ( ) ; optionalArgs . put ( USE_MAPS , false ) ; } if ( ! optionalArgs . containsKey ( USE_MAPS ) ) { optionalArgs . put ( USE_MAPS , false ) ; } JsonReader jr = new JsonReader ( json , optionalArgs ) ; Object obj = jr . readObject ( ) ; jr . close ( ) ; return obj ;


signature:
public class JsonReader { /** * Map args = [ " USE _ MAPS " : true ]
 * Use JsonReader . jsonToJava ( String json , args )
 * Note that the return type will match the JSON type ( array , object , string , long , boolean , or null ) .
 * No longer recommended : Use jsonToJava with USE _ MAPS : true
 * @ param json String of JSON content
 * @ param optionalArgs Map of optional arguments to control customization . See readme file for
 * details on these options .
 * @ return Map where each Map representa an object in the JSON input . */
public static Map jsonToMaps ( String json , Map < String , Object > optionalArgs ) { } }

implementation: try { if ( optionalArgs == null ) { optionalArgs = new HashMap < String , Object > ( ) ; } optionalArgs . put ( USE_MAPS , true ) ; ByteArrayInputStream ba = new ByteArrayInputStream ( json . getBytes ( "UTF-8" ) ) ; JsonReader jr = new JsonReader ( ba , optionalArgs ) ; Object ret = jr . readObject ( ) ; jr . close ( ) ; return adjustOutputMap ( ret ) ; } catch ( UnsupportedEncodingException e ) { throw new JsonIoException ( "Could not convert JSON to Maps because your JVM does not support UTF-8" , e ) ; }


signature:
public class JsonReader { /** * Map args = [ " USE _ MAPS " : true ]
 * Use JsonReader . jsonToJava ( inputStream , args )
 * Note that the return type will match the JSON type ( array , object , string , long , boolean , or null ) .
 * No longer recommended : Use jsonToJava with USE _ MAPS : true
 * @ param inputStream containing JSON content
 * @ param optionalArgs Map of optional arguments to control customization . See readme file for
 * details on these options .
 * @ return Map containing the content from the JSON input . Each Map represents an object from the input . */
public static Map jsonToMaps ( InputStream inputStream , Map < String , Object > optionalArgs ) { } }

implementation: if ( optionalArgs == null ) { optionalArgs = new HashMap < String , Object > ( ) ; } optionalArgs . put ( USE_MAPS , true ) ; JsonReader jr = new JsonReader ( inputStream , optionalArgs ) ; Object ret = jr . readObject ( ) ; jr . close ( ) ; return adjustOutputMap ( ret ) ;


signature:
public class JsonReader { /** * This method is needed to get around the fact that ' this ( ) ' has to be the first method of a constructor . */
static Map makeArgMap ( Map < String , Object > args , boolean useMaps ) { } }

implementation: args . put ( USE_MAPS , useMaps ) ; return args ;


signature:
public class JsonReader { /** * Read JSON input from the stream that was set up in the constructor , turning it into
 * Java Maps ( JsonObject ' s ) . Then , if requested , the JsonObjects can be converted
 * into Java instances .
 * @ return Java Object graph constructed from InputStream supplying
 * JSON serialized content . */
public Object readObject ( ) { } }

implementation:
JsonParser parser = new JsonParser ( input , objsRead , getArgs ( ) ) ; JsonObject < String , Object > root = new JsonObject ( ) ; Object o ; try { o = parser . readValue ( root ) ; if ( o == JsonParser . EMPTY_OBJECT ) { return new JsonObject ( ) ; } } catch ( JsonIoException e ) { throw e ; } catch ( Exception e ) { throw new JsonIoException ( "error parsing JSON value" , e ) ; } Object graph ; if ( o instanceof Object [ ] ) { root . setType ( Object [ ] . class . getName ( ) ) ; root . setTarget ( o ) ; root . put ( "@items" , o ) ; graph = convertParsedMapsToJava ( root ) ; } else { graph = o instanceof JsonObject ? convertParsedMapsToJava ( ( JsonObject ) o ) : o ; } // Allow a complete ' Map ' return ( Javascript style )
if ( useMaps ( ) ) { return o ; } return graph ;


signature:
public class JsonReader { /** * Convert a root JsonObject that represents parsed JSON , into
 * an actual Java object .
 * @ param root JsonObject instance that was the root object from the
 * JSON input that was parsed in an earlier call to JsonReader .
 * @ return a typed Java instance that was serialized into JSON . */
public Object jsonObjectsToJava ( JsonObject root ) { } }

implementation: getArgs ( ) . put ( USE_MAPS , false ) ; return convertParsedMapsToJava ( root ) ;


signature:
public class JsonReader { /** * This method converts a root Map , ( which contains nested Maps
 * and so forth representing a Java Object graph ) , to a Java
 * object instance . The root map came from using the JsonReader
 * to parse a JSON graph ( using the API that puts the graph
 * into Maps , not the typed representation ) .
 * @ param root JsonObject instance that was the root object from the
 * JSON input that was parsed in an earlier call to JsonReader .
 * @ return a typed Java instance that was serialized into JSON . */
protected Object convertParsedMapsToJava ( JsonObject root ) { } }

implementation:
try { Resolver resolver = useMaps ( ) ? new MapResolver ( this ) : new ObjectResolver ( this , ( ClassLoader ) args . get ( CLASSLOADER ) ) ; resolver . createJavaObjectInstance ( Object . class , root ) ; Object graph = resolver . convertMapsToObjects ( ( JsonObject < String , Object > ) root ) ; resolver . cleanup ( ) ; readers . clear ( ) ; return graph ; } catch ( Exception e ) { try { close ( ) ; } catch ( Exception ignored ) { // Exception handled in close ( )
} if ( e instanceof JsonIoException ) { throw ( JsonIoException ) e ; } throw new JsonIoException ( getErrorMessage ( e . getMessage ( ) ) , e ) ; }


signature:
public class ObjectResolver { /** * Walk the Java object fields and copy them from the JSON object to the Java object , performing
 * any necessary conversions on primitives , or deep traversals for field assignments to other objects ,
 * arrays , Collections , or Maps .
 * @ param stack Stack ( Deque ) used for graph traversal .
 * @ param jsonObj a Map - of - Map representation of the current object being examined ( containing all fields ) . */
public void traverseFields ( final Deque < JsonObject < String , Object > > stack , final JsonObject < String , Object > jsonObj ) { } }

implementation:
final Object javaMate = jsonObj . target ; final Iterator < Map . Entry < String , Object > > i = jsonObj . entrySet ( ) . iterator ( ) ; final Class cls = javaMate . getClass ( ) ; while ( i . hasNext ( ) ) { Map . Entry < String , Object > e = i . next ( ) ; String key = e . getKey ( ) ; final Field field = MetaUtils . getField ( cls , key ) ; Object rhs = e . getValue ( ) ; if ( field != null ) { assignField ( stack , jsonObj , field , rhs ) ; } else if ( missingFieldHandler != null ) { handleMissingField ( stack , jsonObj , rhs , key ) ; } // else no handler so ignor .
}


signature:
public class ObjectResolver { /** * Map Json Map object field to Java object field .
 * @ param stack Stack ( Deque ) used for graph traversal .
 * @ param jsonObj a Map - of - Map representation of the current object being examined ( containing all fields ) .
 * @ param field a Java Field object representing where the jsonObj should be converted and stored .
 * @ param rhs the JSON value that will be converted and stored in the ' field ' on the associated
 * Java target object . */
protected void assignField ( final Deque < JsonObject < String , Object > > stack , final JsonObject jsonObj , final Field field , final Object rhs ) { } }

implementation:
final Object target = jsonObj . target ; try { final Class fieldType = field . getType ( ) ; if ( rhs == null ) { // Logically clear field ( allows null to be set against primitive fields , yielding their zero value .
if ( fieldType . isPrimitive ( ) ) { field . set ( target , MetaUtils . convert ( fieldType , "0" ) ) ; } else { field . set ( target , null ) ; } return ; } // If there is a " tree " of objects ( e . g , Map < String , List < Person > > ) , the subobjects may not have an
// @ type on them , if the source of the JSON is from JSON . stringify ( ) . Deep traverse the args and
// mark @ type on the items within the Maps and Collections , based on the parameterized type ( if it
// exists ) .
if ( rhs instanceof JsonObject ) { if ( field . getGenericType ( ) instanceof ParameterizedType ) { // Only JsonObject instances could contain unmarked objects .
markUntypedObjects ( field . getGenericType ( ) , rhs , MetaUtils . getDeepDeclaredFields ( fieldType ) ) ; } // Ensure . type field set on JsonObject
final JsonObject job = ( JsonObject ) rhs ; final String type = job . type ; if ( type == null || type . isEmpty ( ) ) { job . setType ( fieldType . getName ( ) ) ; } } Object special ; if ( rhs == JsonParser . EMPTY_OBJECT ) { final JsonObject jObj = new JsonObject ( ) ; jObj . type = fieldType . getName ( ) ; Object value = createJavaObjectInstance ( fieldType , jObj ) ; field . set ( target , value ) ; } else if ( ( special = readIfMatching ( rhs , fieldType , stack ) ) != null ) { field . set ( target , special ) ; } else if ( rhs . getClass ( ) . isArray ( ) ) { // LHS of assignment is an [ ] field or RHS is an array and LHS is Object
final Object [ ] elements = ( Object [ ] ) rhs ; JsonObject < String , Object > jsonArray = new JsonObject < String , Object > ( ) ; if ( char [ ] . class == fieldType ) { // Specially handle char [ ] because we are writing these
// out as UTF8 strings for compactness and speed .
if ( elements . length == 0 ) { field . set ( target , new char [ ] { } ) ; } else { field . set ( target , ( ( String ) elements [ 0 ] ) . toCharArray ( ) ) ; } } else { jsonArray . put ( "@items" , elements ) ; createJavaObjectInstance ( fieldType , jsonArray ) ; field . set ( target , jsonArray . target ) ; stack . addFirst ( jsonArray ) ; } } else if ( rhs instanceof JsonObject ) { final JsonObject < String , Object > jObj = ( JsonObject ) rhs ; final Long ref = jObj . getReferenceId ( ) ; if ( ref != null ) { // Correct field references
final JsonObject refObject = getReferencedObj ( ref ) ; if ( refObject . target != null ) { field . set ( target , refObject . target ) ; } else { unresolvedRefs . add ( new UnresolvedReference ( jsonObj , field . getName ( ) , ref ) ) ; } } else { // Assign ObjectMap ' s to Object ( or derived ) fields
field . set ( target , createJavaObjectInstance ( fieldType , jObj ) ) ; if ( ! MetaUtils . isLogicalPrimitive ( jObj . getTargetClass ( ) ) ) { stack . addFirst ( ( JsonObject ) rhs ) ; } } } else { if ( MetaUtils . isPrimitive ( fieldType ) ) { field . set ( target , MetaUtils . convert ( fieldType , rhs ) ) ; } else if ( rhs instanceof String && "" . equals ( ( ( String ) rhs ) . trim ( ) ) && fieldType != String . class ) { // Allow " " to null out a non - String field
field . set ( target , null ) ; } else { field . set ( target , rhs ) ; } } } catch ( Exception e ) { String message = e . getClass ( ) . getSimpleName ( ) + " setting field '" + field . getName ( ) + "' on target: " + safeToString ( target ) + " with value: " + rhs ; if ( MetaUtils . loadClassException != null ) { message += " Caused by: " + MetaUtils . loadClassException + " (which created a LinkedHashMap instead of the desired class)" ; } throw new JsonIoException ( message , e ) ; }


signature:
public class ObjectResolver { /** * Try to create an java object from the missing field .
 * Mosly primitive types and jsonObject that contains @ type attribute will
 * be candidate for the missing field callback , others will be ignored .
 * All missing field are stored for later notification
 * @ param stack Stack ( Deque ) used for graph traversal .
 * @ param jsonObj a Map - of - Map representation of the current object being examined ( containing all fields ) .
 * @ param rhs the JSON value that will be converted and stored in the ' field ' on the associated Java target object .
 * @ param missingField name of the missing field in the java object . */
protected void handleMissingField ( final Deque < JsonObject < String , Object > > stack , final JsonObject jsonObj , final Object rhs , final String missingField ) { } }

implementation:
final Object target = jsonObj . target ; try { if ( rhs == null ) { // Logically clear field ( allows null to be set against primitive fields , yielding their zero value .
storeMissingField ( target , missingField , null ) ; return ; } // we have a jsonobject with a type
Object special ; if ( rhs == JsonParser . EMPTY_OBJECT ) { storeMissingField ( target , missingField , null ) ; } else if ( ( special = readIfMatching ( rhs , null , stack ) ) != null ) { storeMissingField ( target , missingField , special ) ; } else if ( rhs . getClass ( ) . isArray ( ) ) { // impossible to determine the array type .
storeMissingField ( target , missingField , null ) ; } else if ( rhs instanceof JsonObject ) { final JsonObject < String , Object > jObj = ( JsonObject ) rhs ; final Long ref = jObj . getReferenceId ( ) ; if ( ref != null ) { // Correct field references
final JsonObject refObject = getReferencedObj ( ref ) ; storeMissingField ( target , missingField , refObject . target ) ; } else { // Assign ObjectMap ' s to Object ( or derived ) fields
// check that jObj as a type
if ( jObj . getType ( ) != null ) { Object createJavaObjectInstance = createJavaObjectInstance ( null , jObj ) ; if ( ! MetaUtils . isLogicalPrimitive ( jObj . getTargetClass ( ) ) ) { stack . addFirst ( ( JsonObject ) rhs ) ; } storeMissingField ( target , missingField , createJavaObjectInstance ) ; } else // no type found , just notify .
{ storeMissingField ( target , missingField , null ) ; } } } else { storeMissingField ( target , missingField , rhs ) ; } } catch ( Exception e ) { String message = e . getClass ( ) . getSimpleName ( ) + " missing field '" + missingField + "' on target: " + safeToString ( target ) + " with value: " + rhs ; if ( MetaUtils . loadClassException != null ) { message += " Caused by: " + MetaUtils . loadClassException + " (which created a LinkedHashMap instead of the desired class)" ; } throw new JsonIoException ( message , e ) ; }


signature:
public class ObjectResolver { /** * stores the missing field and their values to call back the handler at the end of the resolution , cause some
 * reference may need to be resolved later . */
private void storeMissingField ( Object target , String missingField , Object value ) { } }

implementation: missingFields . add ( new Missingfields ( target , missingField , value ) ) ;


signature:
public class ObjectResolver { /** * Process java . util . Collection and it ' s derivatives . Collections are written specially
 * so that the serialization does not expose the Collection ' s internal structure , for
 * example , a TreeSet . All entries are processed , except unresolved references , which
 * are filled in later . For an indexable collection , the unresolved references are set
 * back into the proper element location . For non - indexable collections ( Sets ) , the
 * unresolved references are added via . add ( ) .
 * @ param jsonObj a Map - of - Map representation of the JSON input stream . */
protected void traverseCollection ( final Deque < JsonObject < String , Object > > stack , final JsonObject < String , Object > jsonObj ) { } }

implementation:
final Object [ ] items = jsonObj . getArray ( ) ; if ( items == null || items . length == 0 ) { return ; } final Collection col = ( Collection ) jsonObj . target ; final boolean isList = col instanceof List ; int idx = 0 ; for ( final Object element : items ) { Object special ; if ( element == null ) { col . add ( null ) ; } else if ( element == JsonParser . EMPTY_OBJECT ) { // Handles { }
col . add ( new JsonObject ( ) ) ; } else if ( ( special = readIfMatching ( element , null , stack ) ) != null ) { col . add ( special ) ; } else if ( element instanceof String || element instanceof Boolean || element instanceof Double || element instanceof Long ) { // Allow Strings , Booleans , Longs , and Doubles to be " inline " without Java object decoration ( @ id , @ type , etc . )
col . add ( element ) ; } else if ( element . getClass ( ) . isArray ( ) ) { final JsonObject jObj = new JsonObject ( ) ; jObj . put ( "@items" , element ) ; createJavaObjectInstance ( Object . class , jObj ) ; col . add ( jObj . target ) ; convertMapsToObjects ( jObj ) ; } else // if ( element instanceof JsonObject )
{ final JsonObject jObj = ( JsonObject ) element ; final Long ref = jObj . getReferenceId ( ) ; if ( ref != null ) { JsonObject refObject = getReferencedObj ( ref ) ; if ( refObject . target != null ) { col . add ( refObject . target ) ; } else { unresolvedRefs . add ( new UnresolvedReference ( jsonObj , idx , ref ) ) ; if ( isList ) { // Indexable collection , so set ' null ' as element for now - will be patched in later .
col . add ( null ) ; } } } else { createJavaObjectInstance ( Object . class , jObj ) ; if ( ! MetaUtils . isLogicalPrimitive ( jObj . getTargetClass ( ) ) ) { convertMapsToObjects ( jObj ) ; } col . add ( jObj . target ) ; } } idx ++ ; } jsonObj . remove ( "@items" ) ; // Reduce memory required during processing


signature:
public class ObjectResolver { /** * Traverse the JsonObject associated to an array ( of any type ) . Convert and
 * assign the list of items in the JsonObject ( stored in the @ items field )
 * to each array element . All array elements are processed excluding elements
 * that reference an unresolved object . These are filled in later .
 * @ param stack a Stack ( Deque ) used to support graph traversal .
 * @ param jsonObj a Map - of - Map representation of the JSON input stream . */
protected void traverseArray ( final Deque < JsonObject < String , Object > > stack , final JsonObject < String , Object > jsonObj ) { } }

implementation:
final int len = jsonObj . getLength ( ) ; if ( len == 0 ) { return ; } final Class compType = jsonObj . getComponentType ( ) ; if ( char . class == compType ) { return ; } if ( byte . class == compType ) { // Handle byte [ ] special for performance boost .
jsonObj . moveBytesToMate ( ) ; jsonObj . clearArray ( ) ; return ; } final boolean isPrimitive = MetaUtils . isPrimitive ( compType ) ; final Object array = jsonObj . target ; final Object [ ] items = jsonObj . getArray ( ) ; for ( int i = 0 ; i < len ; i ++ ) { final Object element = items [ i ] ; Object special ; if ( element == null ) { Array . set ( array , i , null ) ; } else if ( element == JsonParser . EMPTY_OBJECT ) { // Use either explicitly defined type in ObjectMap associated to JSON , or array component type .
Object arrayElement = createJavaObjectInstance ( compType , new JsonObject ( ) ) ; Array . set ( array , i , arrayElement ) ; } else if ( ( special = readIfMatching ( element , compType , stack ) ) != null ) { Array . set ( array , i , special ) ; } else if ( isPrimitive ) { // Primitive component type array
Array . set ( array , i , MetaUtils . convert ( compType , element ) ) ; } else if ( element . getClass ( ) . isArray ( ) ) { // Array of arrays
if ( char [ ] . class == compType ) { // Specially handle char [ ] because we are writing these
// out as UTF - 8 strings for compactness and speed .
Object [ ] jsonArray = ( Object [ ] ) element ; if ( jsonArray . length == 0 ) { Array . set ( array , i , new char [ ] { } ) ; } else { final String value = ( String ) jsonArray [ 0 ] ; final int numChars = value . length ( ) ; final char [ ] chars = new char [ numChars ] ; for ( int j = 0 ; j < numChars ; j ++ ) { chars [ j ] = value . charAt ( j ) ; } Array . set ( array , i , chars ) ; } } else { JsonObject < String , Object > jsonObject = new JsonObject < String , Object > ( ) ; jsonObject . put ( "@items" , element ) ; Array . set ( array , i , createJavaObjectInstance ( compType , jsonObject ) ) ; stack . addFirst ( jsonObject ) ; } } else if ( element instanceof JsonObject ) { JsonObject < String , Object > jsonObject = ( JsonObject < String , Object > ) element ; Long ref = jsonObject . getReferenceId ( ) ; if ( ref != null ) { // Connect reference
JsonObject refObject = getReferencedObj ( ref ) ; if ( refObject . target != null ) { // Array element with reference to existing object
Array . set ( array , i , refObject . target ) ; } else { // Array with a forward reference as an element
unresolvedRefs . add ( new UnresolvedReference ( jsonObj , i , ref ) ) ; } } else { // Convert JSON HashMap to Java Object instance and assign values
Object arrayElement = createJavaObjectInstance ( compType , jsonObject ) ; Array . set ( array , i , arrayElement ) ; if ( ! MetaUtils . isLogicalPrimitive ( arrayElement . getClass ( ) ) ) { // Skip walking primitives , primitive wrapper classes , Strings , and Classes
stack . addFirst ( jsonObject ) ; } } } else { if ( element instanceof String && "" . equals ( ( ( String ) element ) . trim ( ) ) && compType != String . class && compType != Object . class ) { // Allow an entry of " " in the array to set the array element to null , * if * the array type is NOT String [ ] and NOT Object [ ]
Array . set ( array , i , null ) ; } else { Array . set ( array , i , element ) ; } } } jsonObj . clearArray ( ) ;


signature:
public class ObjectResolver { /** * Convert the passed in object ( o ) to a proper Java object . If the passed in object ( o ) has a custom reader
 * associated to it , then have it convert the object . If there is no custom reader , then return null .
 * @ param o Object to read ( convert ) . Will be either a JsonObject or a JSON primitive String , long , boolean ,
 * double , or null .
 * @ param compType Class destination type to which the passed in object should be converted to .
 * @ param stack a Stack ( Deque ) used to support graph traversal .
 * @ return Java object converted from the passed in object o , or if there is no custom reader . */
protected Object readIfMatching ( final Object o , final Class compType , final Deque < JsonObject < String , Object > > stack ) { } }

implementation:
if ( o == null ) { throw new JsonIoException ( "Bug in json-io, null must be checked before calling this method." ) ; } if ( compType != null && notCustom ( compType ) ) { return null ; } final boolean isJsonObject = o instanceof JsonObject ; if ( ! isJsonObject && compType == null ) { // If not a JsonObject ( like a Long that represents a date , then compType must be set )
return null ; } Class c ; boolean needsType = false ; // Set up class type to check against reader classes ( specified as @ type , or jObj . target , or compType )
if ( isJsonObject ) { JsonObject jObj = ( JsonObject ) o ; if ( jObj . isReference ( ) ) { return null ; } if ( jObj . target == null ) { // ' @ type ' parameter used ( not target instance )
String typeStr = null ; try { Object type = jObj . type ; if ( type != null ) { typeStr = ( String ) type ; c = MetaUtils . classForName ( ( String ) type , classLoader ) ; } else { if ( compType != null ) { c = compType ; needsType = true ; } else { return null ; } } createJavaObjectInstance ( c , jObj ) ; } catch ( Exception e ) { throw new JsonIoException ( "Class listed in @type [" + typeStr + "] is not found" , e ) ; } } else { // Type inferred from target object
c = jObj . target . getClass ( ) ; } } else { c = compType ; } if ( notCustom ( c ) ) { return null ; } JsonReader . JsonClassReaderBase closestReader = getCustomReader ( c ) ; if ( closestReader == null ) { return null ; } if ( needsType ) { ( ( JsonObject ) o ) . setType ( c . getName ( ) ) ; } Object read ; if ( closestReader instanceof JsonReader . JsonClassReaderEx ) { read = ( ( JsonReader . JsonClassReaderEx ) closestReader ) . read ( o , stack , getReader ( ) . getArgs ( ) ) ; } else { read = ( ( JsonReader . JsonClassReader ) closestReader ) . read ( o , stack ) ; } return read ;


signature:
public class ObjectResolver { /** * node ( no further subtypes in it ' s parameterized type definition ) */
private static void stampTypeOnJsonObject ( final Object o , final Type t ) { } }

implementation: Class clazz = t instanceof Class ? ( Class ) t : getRawType ( t ) ; if ( o instanceof JsonObject && clazz != null ) { JsonObject jObj = ( JsonObject ) o ; if ( ( jObj . type == null || jObj . type . isEmpty ( ) ) && jObj . target == null ) { jObj . type = clazz . getName ( ) ; } }


signature:
public class ObjectResolver { /** * Given the passed in Type t , return the raw type of it , if the passed in value is a ParameterizedType .
 * @ param t Type to attempt to get raw type from .
 * @ return Raw type obtained from the passed in parameterized type or null if T is not a ParameterizedType */
public static Class getRawType ( final Type t ) { } }

implementation: if ( t instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) t ; if ( pType . getRawType ( ) instanceof Class ) { return ( Class ) pType . getRawType ( ) ; } } return null ;


signature:
public class JsonObject { /** * Collection APIs */
public boolean isCollection ( ) { } }

implementation: if ( target instanceof Collection ) { return true ; } if ( containsKey ( "@items" ) && ! containsKey ( "@keys" ) ) { return type != null && ! type . contains ( "[" ) ; } return false ;


signature:
public class JsonObject { /** * Array APIs */
public boolean isArray ( ) { } }

implementation: if ( target == null ) { if ( type != null ) { return type . contains ( "[" ) ; } return containsKey ( "@items" ) && ! containsKey ( "@keys" ) ; } return target . getClass ( ) . isArray ( ) ;


signature:
public class JsonParser { /** * Read a JSON array */
private Object readArray ( JsonObject object ) throws IOException { } }

implementation: final List < Object > array = new ArrayList ( ) ; while ( true ) { final Object o = readValue ( object ) ; if ( o != EMPTY_ARRAY ) { array . add ( o ) ; } final int c = skipWhitespaceRead ( ) ; if ( c == ']' ) { break ; } else if ( c != ',' ) { error ( "Expected ',' or ']' inside array" ) ; } } return array . toArray ( ) ;


signature:
public class JsonParser { /** * Return the specified token from the reader . If it is not found ,
 * throw an IOException indicating that . Converting to c to
 * ( char ) c is acceptable because the ' tokens ' allowed in a
 * JSON input stream ( true , false , null ) are all ASCII . */
private void readToken ( String token ) throws IOException { } }

implementation: final int len = token . length ( ) ; for ( int i = 1 ; i < len ; i ++ ) { int c = input . read ( ) ; if ( c == - 1 ) { error ( "EOF reached while reading token: " + token ) ; } c = Character . toLowerCase ( ( char ) c ) ; int loTokenChar = token . charAt ( i ) ; if ( loTokenChar != c ) { error ( "Expected token: " + token ) ; } }


signature:
public class JsonParser { /** * Read a JSON number
 * @ param c int a character representing the first digit of the number that
 * was already read .
 * @ return a Number ( a Long or a Double ) depending on whether the number is
 * a decimal number or integer . This choice allows all smaller types ( Float , int , short , byte )
 * to be represented as well .
 * @ throws IOException for stream errors or parsing errors . */
private Number readNumber ( int c ) throws IOException { } }

implementation:
final FastPushbackReader in = input ; final StringBuilder number = numBuf ; number . setLength ( 0 ) ; number . appendCodePoint ( c ) ; boolean isFloat = false ; if ( JsonReader . isLenient ( ) && ( c == '-' || c == 'N' || c == 'I' ) ) { // Handle negativity .
final boolean isNeg = ( c == '-' ) ; if ( isNeg ) { // Advance to next character .
c = input . read ( ) ; } // Case " - Infinity " , " Infinity " or " NaN " .
if ( c == 'I' ) { // [ Out of RFC 4627 ] accept NaN / Infinity values
readToken ( "infinity" ) ; return ( isNeg ) ? Double . NEGATIVE_INFINITY : Double . POSITIVE_INFINITY ; } else if ( 'N' == c ) { // [ Out of RFC 4627 ] accept NaN / Infinity values
readToken ( "nan" ) ; return Double . NaN ; } else { // Case this is a number but not " - Infinity " , like " - 2 " . We let the normal code process .
input . unread ( '-' ) ; } } while ( true ) { c = in . read ( ) ; if ( ( c >= '0' && c <= '9' ) || c == '-' || c == '+' ) { number . appendCodePoint ( c ) ; } else if ( c == '.' || c == 'e' || c == 'E' ) { number . appendCodePoint ( c ) ; isFloat = true ; } else if ( c == - 1 ) { break ; } else { in . unread ( c ) ; break ; } } try { if ( isFloat ) { // Floating point number needed
return Double . parseDouble ( number . toString ( ) ) ; } else { return Long . parseLong ( number . toString ( ) ) ; } } catch ( Exception e ) { return ( Number ) error ( "Invalid number: " + number , e ) ; }


signature:
public class JsonParser { /** * Read a JSON string
 * This method assumes the initial quote has already been read .
 * @ return String read from JSON input stream .
 * @ throws IOException for stream errors or parsing errors . */
private String readString ( ) throws IOException { } }

implementation: final StringBuilder str = strBuf ; final StringBuilder hex = hexBuf ; str . setLength ( 0 ) ; int state = STRING_START ; final FastPushbackReader in = input ; while ( true ) { final int c = in . read ( ) ; if ( c == - 1 ) { error ( "EOF reached while reading JSON string" ) ; } if ( state == STRING_START ) { if ( c == '"' ) { break ; } else if ( c == '\\' ) { state = STRING_SLASH ; } else { str . appendCodePoint ( c ) ; } } else if ( state == STRING_SLASH ) { switch ( c ) { case '\\' : str . appendCodePoint ( '\\' ) ; break ; case '/' : str . appendCodePoint ( '/' ) ; break ; case '"' : str . appendCodePoint ( '"' ) ; break ; case '\'' : str . appendCodePoint ( '\'' ) ; break ; case 'b' : str . appendCodePoint ( '\b' ) ; break ; case 'f' : str . appendCodePoint ( '\f' ) ; break ; case 'n' : str . appendCodePoint ( '\n' ) ; break ; case 'r' : str . appendCodePoint ( '\r' ) ; break ; case 't' : str . appendCodePoint ( '\t' ) ; break ; case 'u' : hex . setLength ( 0 ) ; state = HEX_DIGITS ; break ; default : error ( "Invalid character escape sequence specified: " + c ) ; } if ( c != 'u' ) { state = STRING_START ; } } else { if ( ( c >= '0' && c <= '9' ) || ( c >= 'A' && c <= 'F' ) || ( c >= 'a' && c <= 'f' ) ) { hex . appendCodePoint ( ( char ) c ) ; if ( hex . length ( ) == 4 ) { int value = Integer . parseInt ( hex . toString ( ) , 16 ) ; str . appendCodePoint ( value ) ; state = STRING_START ; } } else { error ( "Expected hexadecimal digits" ) ; } } } final String s = str . toString ( ) ; final String translate = stringCache . get ( s ) ; return translate == null ? s : translate ;


signature:
public class JsonParser { /** * Read until non - whitespace character and then return it .
 * This saves extra read / pushback .
 * @ return int representing the next non - whitespace character in the stream .
 * @ throws IOException for stream errors or parsing errors . */
private int skipWhitespaceRead ( ) throws IOException { } }

implementation: FastPushbackReader in = input ; int c ; do { c = in . read ( ) ; } while ( c == ' ' || c == '\n' || c == '\r' || c == '\t' ) ; return c ;


signature:
public class MetaUtils { /** * Globally turn on ( or off ) the ' unsafe ' option of Class construction . The unsafe option
 * is used when all constructors have been tried and the Java class could not be instantiated .
 * @ param state boolean true = on , false = off . */
public static void setUseUnsafe ( boolean state ) { } }

implementation: useUnsafe = state ; if ( state ) { try { unsafe = new Unsafe ( ) ; } catch ( InvocationTargetException e ) { useUnsafe = false ; } }


signature:
public class MetaUtils { /** * Return an instance of of the Java Field class corresponding to the passed in field name .
 * @ param c class containing the field / field name
 * @ param field String name of a field on the class .
 * @ return Field instance if the field with the corresponding name is found , null otherwise . */
public static Field getField ( Class c , String field ) { } }

implementation: return getDeepDeclaredFields ( c ) . get ( field ) ;


signature:
public class MetaUtils { /** * Given the passed in String class name , return the named JVM class .
 * @ param name String name of a JVM class .
 * @ param classLoader ClassLoader to use when searching for JVM classes .
 * @ param failOnClassLoadingError If named class is not loadable off classpath : true will raise JsonIoException ,
 * false will return default LinkedHashMap .
 * @ return Class the named JVM class .
 * @ throws JsonIoException if named Class is invalid or not loadable via the classLoader and failOnClassLoadingError is
 * true */
static Class classForName ( String name , ClassLoader classLoader , boolean failOnClassLoadingError ) { } }

implementation:
if ( name == null || name . isEmpty ( ) ) { throw new JsonIoException ( "Class name cannot be null or empty." ) ; } Class c = nameToClass . get ( name ) ; try { loadClassException = null ; return c == null ? loadClass ( name , classLoader ) : c ; } catch ( Exception e ) { // Remember why in case later we have a problem
loadClassException = e ; if ( failOnClassLoadingError ) { throw new JsonIoException ( "Unable to create class: " + name , e ) ; } return LinkedHashMap . class ; }


signature:
public class MetaUtils { /** * Given the passed in String class name , return the named JVM class .
 * @ param name String name of a JVM class .
 * @ param classLoader ClassLoader to use when searching for JVM classes .
 * @ return Class the named JVM class .
 * @ throws JsonIoException if named Class is invalid . */
static Class classForName ( String name , ClassLoader classLoader ) { } }

implementation: return classForName ( name , classLoader , false ) ;


signature:
public class MetaUtils { /** * loadClass ( ) provided by : Thomas Margreiter */
private static Class loadClass ( String name , ClassLoader classLoader ) throws ClassNotFoundException { } }

implementation: String className = name ; boolean arrayType = false ; Class primitiveArray = null ; while ( className . startsWith ( "[" ) ) { arrayType = true ; if ( className . endsWith ( ";" ) ) { className = className . substring ( 0 , className . length ( ) - 1 ) ; } if ( className . equals ( "[B" ) ) { primitiveArray = byte [ ] . class ; } else if ( className . equals ( "[S" ) ) { primitiveArray = short [ ] . class ; } else if ( className . equals ( "[I" ) ) { primitiveArray = int [ ] . class ; } else if ( className . equals ( "[J" ) ) { primitiveArray = long [ ] . class ; } else if ( className . equals ( "[F" ) ) { primitiveArray = float [ ] . class ; } else if ( className . equals ( "[D" ) ) { primitiveArray = double [ ] . class ; } else if ( className . equals ( "[Z" ) ) { primitiveArray = boolean [ ] . class ; } else if ( className . equals ( "[C" ) ) { primitiveArray = char [ ] . class ; } int startpos = className . startsWith ( "[L" ) ? 2 : 1 ; className = className . substring ( startpos ) ; } Class currentClass = null ; if ( null == primitiveArray ) { try { currentClass = classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { currentClass = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } } if ( arrayType ) { currentClass = ( null != primitiveArray ) ? primitiveArray : Array . newInstance ( currentClass , 0 ) . getClass ( ) ; while ( name . startsWith ( "[[" ) ) { currentClass = Array . newInstance ( currentClass , 0 ) . getClass ( ) ; name = name . substring ( 1 ) ; } } return currentClass ;


signature:
public class MetaUtils { /** * Strip leading and trailing double quotes from the passed in String . */
static String removeLeadingAndTrailingQuotes ( String s ) { } }

implementation: Matcher m = extraQuotes . matcher ( s ) ; if ( m . find ( ) ) { s = m . group ( 2 ) ; } return s ;


signature:
public class MetaUtils { /** * < p > C language malloc ( ) for Java
 * < / p > < p >
 * Create a new instance of the passed in Class . This method will make a valiant effort to instantiate
 * the passed in Class , including calling all of its constructors until successful . The order they
 * are tried are public with the fewest arguments first to private with the most arguments . If , after
 * exhausting all constructors , then it will attempt using the ' unsafe allocate ' from Sun . This step is
 * optional - by default it will use this if on a Sun ( Oracle ) JVM unless MetaUtil . setUseUnsafe ( false ) is called .
 * < / p > < p >
 * This method will handle common interfaces , such as Collection , Map , etc . which commonly show up in
 * parameterized types . Any other interface passed to this method will cause a JsonIoException to be thrown .
 * < / p > < p >
 * To improve performance , when called a 2nd time for the same Class , the constructor that was successfully
 * used to construct the instance will be retrieved from an internal cache .
 * @ param c Class to instantiate
 * @ return an instance of the instantiated class . This instance is intended to have its fields ' stuffed ' by
 * direct assignment , not called via setter methods .
 * @ throws JsonIoException if it cannot instantiate the passed in class . */
public static Object newInstance ( Class c ) { } }

implementation:
if ( unmodifiableSortedMap . getClass ( ) . isAssignableFrom ( c ) ) { return new TreeMap ( ) ; } if ( unmodifiableMap . getClass ( ) . isAssignableFrom ( c ) ) { return new LinkedHashMap ( ) ; } if ( unmodifiableSortedSet . getClass ( ) . isAssignableFrom ( c ) ) { return new TreeSet ( ) ; } if ( unmodifiableSet . getClass ( ) . isAssignableFrom ( c ) ) { return new LinkedHashSet ( ) ; } if ( unmodifiableCollection . getClass ( ) . isAssignableFrom ( c ) ) { return new ArrayList ( ) ; } if ( c . isInterface ( ) ) { throw new JsonIoException ( "Cannot instantiate unknown interface: " + c . getName ( ) ) ; } // Constructor not cached , go find a constructor
Object [ ] constructorInfo = constructors . get ( c ) ; if ( constructorInfo != null ) { // Constructor was cached
Constructor constructor = ( Constructor ) constructorInfo [ 0 ] ; if ( constructor == null && useUnsafe ) { // null constructor - - > set to null when object instantiated with unsafe . allocateInstance ( )
try { return unsafe . allocateInstance ( c ) ; } catch ( Exception e ) { // Should never happen , as the code that fetched the constructor was able to instantiate it once already
throw new JsonIoException ( "Could not instantiate " + c . getName ( ) , e ) ; } } if ( constructor == null ) { throw new JsonIoException ( "No constructor found to instantiate " + c . getName ( ) ) ; } Boolean useNull = ( Boolean ) constructorInfo [ 1 ] ; Class [ ] paramTypes = constructor . getParameterTypes ( ) ; if ( paramTypes == null || paramTypes . length == 0 ) { try { return constructor . newInstance ( ) ; } catch ( Exception e ) { // Should never happen , as the code that fetched the constructor was able to instantiate it once already
throw new JsonIoException ( "Could not instantiate " + c . getName ( ) , e ) ; } } Object [ ] values = fillArgs ( paramTypes , useNull ) ; try { return constructor . newInstance ( values ) ; } catch ( Exception e ) { // Should never happen , as the code that fetched the constructor was able to instantiate it once already
throw new JsonIoException ( "Could not instantiate " + c . getName ( ) , e ) ; } } Object [ ] ret = newInstanceEx ( c ) ; constructors . put ( c , new Object [ ] { ret [ 1 ] , ret [ 2 ] } ) ; return ret [ 0 ] ;


signature:
public class MetaUtils { /** * Returns an array with the following :
 * < ol >
 * < li > object instance < / li >
 * < li > constructor < / li >
 * < li > a Boolean , true if all constructor arguments are to be " null " < / li >
 * < / ol > */
static Object [ ] newInstanceEx ( Class c ) { } }

implementation:
try { Constructor constructor = c . getConstructor ( emptyClassArray ) ; if ( constructor != null ) { return new Object [ ] { constructor . newInstance ( ) , constructor , true } ; } // No empty arg constructor
return tryOtherConstruction ( c ) ; } catch ( Exception e ) { // OK , this class does not have a public no - arg constructor . Instantiate with
// first constructor found , filling in constructor values with null or
// defaults for primitives .
return tryOtherConstruction ( c ) ; }


signature:
public class MetaUtils { /** * Brute force attempt to locate a constructor to construct the passed in Class . This involves trying all
 * constructors , public , protected , package - private , and private . It will try with null arguments as well
 * as it will make a 2nd attempt with populated values for some known types ( Collection classes , Dates , Strings ,
 * primitive wrappers , TimeZone , Calendar ) .
 * @ param c Class to instantiate
 * @ return an Object [ ] containing three ( 3 ) elements . Position 0 is the instance of the class , position 1
 * is the constructor used , and position 2 indicates whether fillArgs was called with useNull or ! useNull . */
static Object [ ] tryOtherConstruction ( Class c ) { } }

implementation:
Constructor [ ] constructors = c . getDeclaredConstructors ( ) ; if ( constructors . length == 0 ) { throw new JsonIoException ( "Cannot instantiate '" + c . getName ( ) + "' - Primitive, interface, array[] or void" ) ; } // Sort constructors - public , protected , private , package - private
List < Constructor > constructorList = Arrays . asList ( constructors ) ; Collections . sort ( constructorList , new Comparator < Constructor > ( ) { public int compare ( Constructor c1 , Constructor c2 ) { int c1Vis = c1 . getModifiers ( ) ; int c2Vis = c2 . getModifiers ( ) ; if ( c1Vis == c2Vis ) { // both are public , protected , private , etc . Compare by arguments .
return compareConstructors ( c1 , c2 ) ; } if ( isPublic ( c1Vis ) != isPublic ( c2Vis ) ) { // favor ' public ' as first
return isPublic ( c1Vis ) ? - 1 : 1 ; } if ( isProtected ( c1Vis ) != isProtected ( c2Vis ) ) { // favor protected 2nd
return isProtected ( c1Vis ) ? - 1 : 1 ; } if ( isPrivate ( c1Vis ) != isPrivate ( c2Vis ) ) { // favor private last
return isPrivate ( c1Vis ) ? 1 : - 1 ; } return 0 ; } } ) ; // Try each constructor ( public , protected , private , package - private ) with null values for non - primitives .
for ( Constructor constructor : constructorList ) { constructor . setAccessible ( true ) ; Class [ ] argTypes = constructor . getParameterTypes ( ) ; Object [ ] values = fillArgs ( argTypes , true ) ; try { return new Object [ ] { constructor . newInstance ( values ) , constructor , true } ; } catch ( Exception ignored ) { } } // Try each constructor ( public , protected , private , package - private ) with non - null values for non - primitives .
for ( Constructor constructor : constructorList ) { constructor . setAccessible ( true ) ; Class [ ] argTypes = constructor . getParameterTypes ( ) ; Object [ ] values = fillArgs ( argTypes , false ) ; try { return new Object [ ] { constructor . newInstance ( values ) , constructor , false } ; } catch ( Exception ignored ) { } } // Try instantiation via unsafe
// This may result in heapdumps for e . g . ConcurrentHashMap or can cause problems when the class is not initialized
// Thats why we try ordinary constructors first
if ( useUnsafe ) { try { return new Object [ ] { unsafe . allocateInstance ( c ) , null , null } ; } catch ( Exception ignored ) { } } throw new JsonIoException ( "Could not instantiate " + c . getName ( ) + " using any constructor" ) ;


signature:
public class MetaUtils { /** * When two constructors have the same access type ( both public , both private , etc . )
 * then compare constructors by parameter length ( fewer params comes before more params ) .
 * If parameter count is the same , then compare by parameter Class names . If those are equal ,
 * which should never happen , then the constructurs are equal . */
private static int compareConstructors ( Constructor c1 , Constructor c2 ) { } }

implementation:
Class [ ] c1ParamTypes = c1 . getParameterTypes ( ) ; Class [ ] c2ParamTypes = c2 . getParameterTypes ( ) ; if ( c1ParamTypes . length != c2ParamTypes . length ) { // negative value if c1 has less ( less parameters will be chosen ahead of more ) , positive value otherwise .
return c1ParamTypes . length - c2ParamTypes . length ; } // Has same number of parameters . s
int len = c1ParamTypes . length ; for ( int i = 0 ; i < len ; i ++ ) { Class class1 = c1ParamTypes [ i ] ; Class class2 = c2ParamTypes [ i ] ; int compare = class1 . getName ( ) . compareTo ( class2 . getName ( ) ) ; if ( compare != 0 ) { return compare ; } } return 0 ;


signature:
public class MetaUtils { /** * Return an Object [ ] of instance values that can be passed into a given Constructor . This method
 * will return an array of nulls if useNull is true , otherwise it will return sensible values for
 * primitive classes , and null for non - known primitive / primitive wrappers . This class is used
 * when attempting to call constructors on Java objects to get them instantiated , since there is no
 * ' malloc ' in Java . */
static Object [ ] fillArgs ( Class [ ] argTypes , boolean useNull ) { } }

implementation:
final Object [ ] values = new Object [ argTypes . length ] ; for ( int i = 0 ; i < argTypes . length ; i ++ ) { final Class argType = argTypes [ i ] ; if ( isPrimitive ( argType ) ) { values [ i ] = convert ( argType , null ) ; } else if ( useNull ) { values [ i ] = null ; } else { if ( argType == String . class ) { values [ i ] = "" ; } else if ( argType == Date . class ) { values [ i ] = new Date ( ) ; } else if ( List . class . isAssignableFrom ( argType ) ) { values [ i ] = new ArrayList ( ) ; } else if ( SortedSet . class . isAssignableFrom ( argType ) ) { values [ i ] = new TreeSet ( ) ; } else if ( Set . class . isAssignableFrom ( argType ) ) { values [ i ] = new LinkedHashSet ( ) ; } else if ( SortedMap . class . isAssignableFrom ( argType ) ) { values [ i ] = new TreeMap ( ) ; } else if ( Map . class . isAssignableFrom ( argType ) ) { values [ i ] = new LinkedHashMap ( ) ; } else if ( Collection . class . isAssignableFrom ( argType ) ) { values [ i ] = new ArrayList ( ) ; } else if ( Calendar . class . isAssignableFrom ( argType ) ) { values [ i ] = Calendar . getInstance ( ) ; } else if ( TimeZone . class . isAssignableFrom ( argType ) ) { values [ i ] = TimeZone . getDefault ( ) ; } else if ( argType == BigInteger . class ) { values [ i ] = BigInteger . TEN ; } else if ( argType == BigDecimal . class ) { values [ i ] = BigDecimal . TEN ; } else if ( argType == StringBuilder . class ) { values [ i ] = new StringBuilder ( ) ; } else if ( argType == StringBuffer . class ) { values [ i ] = new StringBuffer ( ) ; } else if ( argType == Locale . class ) { values [ i ] = Locale . FRANCE ; // overwritten
} else if ( argType == Class . class ) { values [ i ] = String . class ; } else if ( argType == Timestamp . class ) { values [ i ] = new Timestamp ( System . currentTimeMillis ( ) ) ; } else if ( argType == java . sql . Date . class ) { values [ i ] = new java . sql . Date ( System . currentTimeMillis ( ) ) ; } else if ( argType == URL . class ) { try { values [ i ] = new URL ( "http://localhost" ) ; // overwritten
} catch ( MalformedURLException e ) { values [ i ] = null ; } } else if ( argType == Object . class ) { values [ i ] = new Object ( ) ; } else { values [ i ] = null ; } } } return values ;


signature:
public class JsonWriter { /** * Used internally to substitute type names . For example , ' java . util . ArrayList , could have a substitute
 * type name of ' alist ' . Set substitute type names using the TYPE _ NAME _ MAP option .
 * @ param typeName String name of type to substitute .
 * @ return String substituted name , or null if there is no substitute . */
protected String getSubstituteTypeNameIfExists ( String typeName ) { } }

implementation: if ( typeNameMap == null ) { return null ; } return typeNameMap . get ( typeName ) ;


signature:
public class JsonWriter { /** * Used internally to substitute type names . For example , ' java . util . ArrayList , could have a substitute
 * type name of ' alist ' . Set substitute type names using the TYPE _ NAME _ MAP option .
 * @ param typeName String name of type to substitute .
 * @ return String substituted type name . */
protected String getSubstituteTypeName ( String typeName ) { } }

implementation: if ( typeNameMap == null ) { return typeName ; } String shortName = typeNameMap . get ( typeName ) ; return shortName == null ? typeName : shortName ;


signature:
public class JsonWriter { /** * Convert a Java Object to a JSON String .
 * @ param item Object to convert to a JSON String .
 * @ param optionalArgs ( optional ) Map of extra arguments indicating how dates are formatted ,
 * what fields are written out ( optional ) . For Date parameters , use the public static
 * DATE _ TIME key , and then use the ISO _ DATE or ISO _ DATE _ TIME indicators . Or you can specify
 * your own custom SimpleDateFormat String , or you can associate a SimpleDateFormat object ,
 * in which case it will be used . This setting is for both java . util . Date and java . sql . Date .
 * If the DATE _ FORMAT key is not used , then dates will be formatted as longs . This long can
 * be turned back into a date by using ' new Date ( longValue ) ' .
 * @ return String containing JSON representation of passed in object root . */
public static String objectToJson ( Object item , Map < String , Object > optionalArgs ) { } }

implementation: try { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; JsonWriter writer = new JsonWriter ( stream , optionalArgs ) ; writer . write ( item ) ; writer . close ( ) ; return new String ( stream . toByteArray ( ) , "UTF-8" ) ; } catch ( Exception e ) { throw new JsonIoException ( "Unable to convert object to JSON" , e ) ; }


signature:
public class JsonWriter { /** * Format the passed in JSON string in a nice , human readable format .
 * @ param json String input JSON
 * @ param readingArgs ( optional ) Map of extra arguments for parsing json . Can be null .
 * @ param writingArgs ( optional ) Map of extra arguments for writing out json . Can be null .
 * @ return String containing equivalent JSON , formatted nicely for human readability . */
public static String formatJson ( String json , Map readingArgs , Map writingArgs ) { } }

implementation: Map args = new HashMap ( ) ; if ( readingArgs != null ) { args . putAll ( readingArgs ) ; } args . put ( JsonReader . USE_MAPS , true ) ; Object obj = JsonReader . jsonToJava ( json , args ) ; args . clear ( ) ; if ( writingArgs != null ) { args . putAll ( writingArgs ) ; } args . put ( PRETTY_PRINT , true ) ; return objectToJson ( obj , args ) ;


signature:
public class JsonWriter { /** * tab the JSON output by the given number of characters specified by delta .
 * @ param output Writer being used for JSON outpt .
 * @ param delta int number of characters to tab .
 * @ throws IOException */
private void tab ( Writer output , int delta ) throws IOException { } }

implementation: if ( ! isPrettyPrint ) { return ; } output . write ( NEW_LINE ) ; depth += delta ; for ( int i = 0 ; i < depth ; i ++ ) { output . write ( "  " ) ; }


signature:
public class JsonWriter { /** * Write the passed in object ( o ) to the JSON output stream , if and only if , there is a custom
 * writer associated to the Class of object ( o ) .
 * @ param o Object to be ( potentially written )
 * @ param showType boolean indicating whether or not to show @ type .
 * @ param output Writer where the actual JSON is being written to .
 * @ return boolean true if written , false is there is no custom writer for the passed in object . */
public boolean writeIfMatching ( Object o , boolean showType , Writer output ) { } }

implementation: if ( neverShowType ) { showType = false ; } Class c = o . getClass ( ) ; if ( notCustom . contains ( c ) ) { return false ; } try { return writeCustom ( c , o , showType , output ) ; } catch ( IOException e ) { throw new JsonIoException ( "Unable to write custom formatted object:" , e ) ; }


signature:
public class JsonWriter { /** * Write the passed in array element to the JSON output , if any only if , there is a customer writer
 * for the class of the instance ' o ' .
 * @ param arrayComponentClass Class type of the array
 * @ param o Object instance to write
 * @ param showType boolean indicating whether or not @ type should be output .
 * @ param output Writer to write the JSON to ( if there is a custom writer for o ' s Class ) .
 * @ return true if the array element was written , false otherwise . */
public boolean writeArrayElementIfMatching ( Class arrayComponentClass , Object o , boolean showType , Writer output ) { } }

implementation: if ( ! o . getClass ( ) . isAssignableFrom ( arrayComponentClass ) || notCustom . contains ( o . getClass ( ) ) ) { return false ; } try { return writeCustom ( arrayComponentClass , o , showType , output ) ; } catch ( IOException e ) { throw new JsonIoException ( "Unable to write custom formatted object as array element:" , e ) ; }


signature:
public class JsonWriter { /** * Perform the actual custom writing for an array element that has a custom writer .
 * @ param arrayComponentClass Class type of the array
 * @ param o Object instance to write
 * @ param showType boolean indicating whether or not @ type should be output .
 * @ param output Writer to write the JSON to ( if there is a custom writer for o ' s Class ) .
 * @ return true if the array element was written , false otherwise . */
protected boolean writeCustom ( Class arrayComponentClass , Object o , boolean showType , Writer output ) throws IOException { } }

implementation: if ( neverShowType ) { showType = false ; } JsonClassWriterBase closestWriter = getCustomWriter ( arrayComponentClass ) ; if ( closestWriter == null ) { return false ; } if ( writeOptionalReference ( o ) ) { return true ; } boolean referenced = objsReferenced . containsKey ( o ) ; if ( closestWriter instanceof JsonClassWriter ) { JsonClassWriter writer = ( JsonClassWriter ) closestWriter ; if ( writer . hasPrimitiveForm ( ) ) { if ( ( ! referenced && ! showType ) || closestWriter instanceof Writers . JsonStringWriter ) { if ( writer instanceof Writers . DateWriter ) { ( ( Writers . DateWriter ) writer ) . writePrimitiveForm ( o , output , args ) ; } else { writer . writePrimitiveForm ( o , output ) ; } return true ; } } } output . write ( '{' ) ; tabIn ( ) ; if ( referenced ) { writeId ( getId ( o ) ) ; if ( showType ) { output . write ( ',' ) ; newLine ( ) ; } } if ( showType ) { writeType ( o , output ) ; } if ( referenced || showType ) { output . write ( ',' ) ; newLine ( ) ; } if ( closestWriter instanceof JsonClassWriterEx ) { ( ( JsonClassWriterEx ) closestWriter ) . write ( o , showType || referenced , output , args ) ; } else { ( ( JsonClassWriter ) closestWriter ) . write ( o , showType || referenced , output ) ; } tabOut ( ) ; output . write ( '}' ) ; return true ;


signature:
public class JsonWriter { /** * Fetch the customer writer for the passed in Class . If it is cached ( already associated to the
 * passed in Class ) , return the same instance , otherwise , make a call to get the custom writer
 * and store that result .
 * @ param c Class of object for which fetch a custom writer
 * @ return JsonClassWriter / JsonClassWriterEx for the custom class ( if one exists ) , null otherwise . */
private JsonClassWriterBase getCustomWriter ( Class c ) { } }

implementation: JsonClassWriterBase writer = writerCache . get ( c ) ; if ( writer == null ) { writer = forceGetCustomWriter ( c ) ; writerCache . put ( c , writer ) ; } return writer == nullWriter ? null : writer ;


signature:
public class JsonWriter { /** * Fetch the customer writer for the passed in Class . This method always fetches the custom writer , doing
 * the complicated inheritance distance checking . This method is only called when a cache miss has happened .
 * A sentinal ' nullWriter ' is returned when no custom writer is found . This prevents future cache misses
 * from re - attempting to find custom writers for classes that do not have a custom writer .
 * @ param c Class of object for which fetch a custom writer
 * @ return JsonClassWriter / JsonClassWriterEx for the custom class ( if one exists ) , nullWriter otherwise . */
private JsonClassWriterBase forceGetCustomWriter ( Class c ) { } }

implementation: JsonClassWriterBase closestWriter = nullWriter ; int minDistance = Integer . MAX_VALUE ; for ( Map . Entry < Class , JsonClassWriterBase > entry : writers . entrySet ( ) ) { Class clz = entry . getKey ( ) ; if ( clz == c ) { return entry . getValue ( ) ; } int distance = MetaUtils . getDistance ( clz , c ) ; if ( distance < minDistance ) { minDistance = distance ; closestWriter = entry . getValue ( ) ; } } return closestWriter ;


signature:
public class JsonWriter { /** * Write the passed in Java object in JSON format .
 * @ param obj Object any Java Object or JsonObject . */
public void write ( Object obj ) { } }

implementation: traceReferences ( obj ) ; objVisited . clear ( ) ; try { writeImpl ( obj , true ) ; } catch ( Exception e ) { throw new JsonIoException ( "Error writing object to JSON:" , e ) ; } flush ( ) ; objVisited . clear ( ) ; objsReferenced . clear ( ) ;


signature:
public class JsonWriter { /** * Walk object graph and visit each instance , following each field , each Collection , Map and so on .
 * Tracks visited to handle cycles and to determine if an item is referenced elsewhere . If an
 * object is never referenced more than once , no @ id field needs to be emitted for it .
 * @ param root Object to be deeply traced . The objVisited and objsReferenced Maps will be written to
 * during the trace . */
protected void traceReferences ( Object root ) { } }

implementation:
if ( root == null ) { return ; } Map < Class , List < Field > > fieldSpecifiers = ( Map ) args . get ( FIELD_SPECIFIERS ) ; final Deque < Object > stack = new ArrayDeque < Object > ( ) ; stack . addFirst ( root ) ; final Map < Object , Long > visited = objVisited ; final Map < Object , Long > referenced = objsReferenced ; while ( ! stack . isEmpty ( ) ) { final Object obj = stack . removeFirst ( ) ; if ( ! MetaUtils . isLogicalPrimitive ( obj . getClass ( ) ) ) { Long id = visited . get ( obj ) ; if ( id != null ) { // Only write an object once .
if ( id == ZERO ) { // 2nd time this object has been seen , so give it a unique ID and mark it referenced
id = identity ++ ; visited . put ( obj , id ) ; referenced . put ( obj , id ) ; } continue ; } else { // Initially , mark an object with 0 as the ID , in case it is never referenced ,
// we don ' t waste the memory to store a Long instance that is never used .
visited . put ( obj , ZERO ) ; } } final Class clazz = obj . getClass ( ) ; if ( clazz . isArray ( ) ) { if ( ! MetaUtils . isLogicalPrimitive ( clazz . getComponentType ( ) ) ) { // Speed up : do not traceReferences of primitives , they cannot reference anything
final int len = Array . getLength ( obj ) ; for ( int i = 0 ; i < len ; i ++ ) { final Object o = Array . get ( obj , i ) ; if ( o != null ) { // Slight perf gain ( null is legal )
stack . addFirst ( o ) ; } } } } else if ( Map . class . isAssignableFrom ( clazz ) ) { // Speed up - logically walk maps , as opposed to following their internal structure .
Map map = ( Map ) obj ; for ( final Object item : map . entrySet ( ) ) { final Map . Entry entry = ( Map . Entry ) item ; if ( entry . getValue ( ) != null ) { stack . addFirst ( entry . getValue ( ) ) ; } if ( entry . getKey ( ) != null ) { stack . addFirst ( entry . getKey ( ) ) ; } } } else if ( Collection . class . isAssignableFrom ( clazz ) ) { for ( final Object item : ( Collection ) obj ) { if ( item != null ) { stack . addFirst ( item ) ; } } } else { // Speed up : do not traceReferences of primitives , they cannot reference anything
if ( ! MetaUtils . isLogicalPrimitive ( obj . getClass ( ) ) ) { traceFields ( stack , obj , fieldSpecifiers ) ; } } }


signature:
public class JsonWriter { /** * Reach - ability trace to visit all objects within the graph to be written .
 * This API will handle any object , using either reflection APIs or by
 * consulting a specified FIELD _ SPECIFIERS map if provided .
 * @ param stack Deque used to manage descent into graph ( rather than using Java stack . ) This allows for
 * much larger graph processing .
 * @ param obj Object root of graph
 * @ param fieldSpecifiers Map of optional field specifiers , which are used to override the field list returned by
 * the JDK reflection operations . This allows a subset of the actual fields on an object to be serialized . */
protected void traceFields ( final Deque < Object > stack , final Object obj , final Map < Class , List < Field > > fieldSpecifiers ) { } }

implementation:
// If caller has special Field specifier for a given class
// then use it , otherwise use reflection .
Collection < Field > fields = getFieldsUsingSpecifier ( obj . getClass ( ) , fieldSpecifiers ) ; Collection < Field > fieldsBySpec = fields ; if ( fields == null ) { // Trace fields using reflection
fields = MetaUtils . getDeepDeclaredFields ( obj . getClass ( ) ) . values ( ) ; } for ( final Field field : fields ) { if ( ( field . getModifiers ( ) & Modifier . TRANSIENT ) != 0 ) { if ( fieldsBySpec == null || ! fieldsBySpec . contains ( field ) ) { // Skip tracing transient fields EXCEPT when the field is listed explicitly by using the fieldSpecifiers Map .
// In that case , the field must be traced , even though it is transient .
continue ; } } try { final Object o = field . get ( obj ) ; if ( o != null && ! MetaUtils . isLogicalPrimitive ( o . getClass ( ) ) ) { // Trace through objects that can reference other objects
stack . addFirst ( o ) ; } } catch ( Exception ignored ) { } }


signature:
public class JsonWriter { /** * Main entry point ( mostly used internally , but may be called from a Custom JSON writer ) .
 * This method will write out whatever object type it is given , including JsonObject ' s .
 * It will handle null , detecting if a custom writer should be called , array , array of
 * JsonObject , Map , Map of JsonObjects , Collection , Collection of JsonObject , any regular
 * object , or a JsonObject representing a regular object .
 * @ param obj Object to be written
 * @ param showType if set to true , the @ type tag will be output . If false , it will be
 * dropped .
 * @ throws IOException if one occurs on the underlying output stream . */
public void writeImpl ( Object obj , boolean showType ) throws IOException { } }

implementation: writeImpl ( obj , showType , true , true ) ;