private static ClassAndMethod internalGetClassForFieldName ( String fieldName , Class < ? > classToLookForFieldIn , boolean isForArray ) { Method found = null ; //precalc the field name as a setter to use for each method test. String fieldNameAsASetter = new StringBuilder ( "set" ) . append ( fieldName . substring ( 0 , 1 ) . toUpperCase ( ) ) . append ( fieldName . substring ( 1 ) ) . toString ( ) ; //hunt for any matching setter in the object for ( Method m : classToLookForFieldIn . getMethods ( ) ) { String methodName = m . getName ( ) ; //eligible setters must only accept a single argument. if ( m . getParameterTypes ( ) . length == 1 && methodName . equals ( fieldNameAsASetter ) ) { found = m ; break ; } } //at the mo, if we don't match a setter, we sysout a warning, this will likely need to become a toggle. if ( found == null ) { if ( DataModelSerializer . IGNORE_UNKNOWN_FIELDS ) { return null ; } else { throw new IllegalStateException ( "Data Model Error: Found unexpected JSON field " + fieldName + " supposedly for in class " + classToLookForFieldIn . getName ( ) ) ; } } else { ClassAndMethod cm = new ClassAndMethod ( ) ; cm . m = found ; if ( isForArray ) { //for an array we return the type of the collection, eg String for List<String> instead of List. Type t = found . getGenericParameterTypes ( ) [ 0 ] ; cm . cls = getClassForType ( t ) ; return cm ; } else { cm . cls = found . getParameterTypes ( ) [ 0 ] ; return cm ; } } }
Utility method given a JSON field name and an associated POJO it will hunt for the appropriate setter to use and if located return the type the setter expects along with a reflected reference to the method itself .