Type-munging for field setting and method invocation.
Conforms to LC3 specification
554296
static Object coerceTypeImpl(Class<?> type, Object value)
    {
        if (value != null && value.getClass() == type) {
            return value;
        }

        switch (getJSTypeCode(value)) {

        case JSTYPE_NULL:
            // raise error if type.isPrimitive()
            if (type.isPrimitive()) {
                reportConversionError(value, type);
            }
            return null;

        case JSTYPE_UNDEFINED:
            if (type == ScriptRuntime.StringClass ||
                type == ScriptRuntime.ObjectClass) {
                return "undefined";
            }
            reportConversionError("undefined", type);
            break;

        case JSTYPE_BOOLEAN:
            // Under LC3, only JS Booleans can be coerced into a Boolean value
            if (type == Boolean.TYPE ||
                type == ScriptRuntime.BooleanClass ||
                type == ScriptRuntime.ObjectClass) {
                return value;
            }
            else if (type == ScriptRuntime.StringClass) {
                return value.toString();
            }
            else {
                reportConversionError(value, type);
            }
            break;

        case JSTYPE_NUMBER:
            if (type == ScriptRuntime.StringClass) {
                return ScriptRuntime.toString(value);
            }
            else if (type == ScriptRuntime.ObjectClass) {
                Context context = Context.getCurrentContext();
                if(context.hasFeature(Context.FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE)) {
                    //to process numbers like 2.0 as 2 without decimal place
                    long roundedValue = Math.round(toDouble(value));
                    if(roundedValue == toDouble(value)) {
                        return coerceToNumber(Long.TYPE, value);
                    }
                }
                return coerceToNumber(Double.TYPE, value);
            }
            else if ((type.isPrimitive() && type != Boolean.TYPE) ||
                     ScriptRuntime.NumberClass.isAssignableFrom(type)) {
                return coerceToNumber(type, value);
            }
            else {
                reportConversionError(value, type);
            }
            break;

        case JSTYPE_STRING:
            if (type == ScriptRuntime.StringClass || type.isInstance(value)) {
                return value.toString();
            }
            else if (type == Character.TYPE
                     || type == ScriptRuntime.CharacterClass)
            {
                // Special case for converting a single char string to a
                // character
                // Placed here because it applies *only* to JS strings,
                // not other JS objects converted to strings
                if (((CharSequence)value).length() == 1) {
                    return Character.valueOf(((CharSequence)value).charAt(0));
                }
                return coerceToNumber(type, value);
            }
            else if ((type.isPrimitive() && type != Boolean.TYPE)
                     || ScriptRuntime.NumberClass.isAssignableFrom(type))
            {
                return coerceToNumber(type, value);
            }
            else {
                reportConversionError(value, type);
            }
            break;

        case JSTYPE_JAVA_CLASS:
            if (value instanceof Wrapper) {
                value = ((Wrapper)value).unwrap();
            }

            if (type == ScriptRuntime.ClassClass ||
                type == ScriptRuntime.ObjectClass) {
                return value;
            }
            else if (type == ScriptRuntime.StringClass) {
                return value.toString();
            }
            else {
                reportConversionError(value, type);
            }
            break;

        case JSTYPE_JAVA_OBJECT:
        case JSTYPE_JAVA_ARRAY:
            if (value instanceof Wrapper) {
              value = ((Wrapper)value).unwrap();
            }
            if (type.isPrimitive()) {
                if (type == Boolean.TYPE) {
                    reportConversionError(value, type);
                }
                return coerceToNumber(type, value);
            }
          if (type == ScriptRuntime.StringClass) {
                return value.toString();
            }
            if (type.isInstance(value)) {
                return value;
            }
            reportConversionError(value, type);
            break;

        case JSTYPE_OBJECT:
            if (type == ScriptRuntime.StringClass) {
                return ScriptRuntime.toString(value);
            }
            else if (type.isPrimitive()) {
                if (type == Boolean.TYPE) {
                    reportConversionError(value, type);
                }
                return coerceToNumber(type, value);
            }
            else if (type.isInstance(value)) {
                return value;
            }
            else if (type == ScriptRuntime.DateClass
                     && value instanceof NativeDate)
            {
                double time = ((NativeDate)value).getJSTimeValue();
                // XXX: This will replace NaN by 0
                return new Date((long)time);
            }
            else if (type.isArray() && value instanceof NativeArray) {
                // Make a new java array, and coerce the JS array components
                // to the target (component) type.
                NativeArray array = (NativeArray) value;
                long length = array.getLength();
                Class<?> arrayType = type.getComponentType();
                Object Result = Array.newInstance(arrayType, (int)length);
                for (int i = 0 ; i < length ; ++i) {
                    try  {
                        Array.set(Result, i, coerceTypeImpl(
                                arrayType, array.get(i, array)));
                    }
                    catch (EvaluatorException ee) {
                        reportConversionError(value, type);
                    }
                }

                return Result;
            }
            else if (value instanceof Wrapper) {
                value = ((Wrapper)value).unwrap();
                if (type.isInstance(value))
                    return value;
                reportConversionError(value, type);
            }
            else if (type.isInterface() && (value instanceof NativeObject
                    || value instanceof NativeFunction)) {
                // Try to use function/object as implementation of Java interface.
                return createInterfaceAdapter(type, (ScriptableObject) value);
            } else {
                reportConversionError(value, type);
            }
            break;
        }

        return value;
    }
1223173
private static int[] makeFields(int[] fields, TupleTypeInfo<?> type) {
		int inLength = type.getArity();
		
		// null parameter means all fields are considered
		if (fields == null || fields.length == 0) {
			fields = new int[inLength];
			for (int i = 0; i < inLength; i++) {
				fields[i] = i;
			}
			return fields;
		} else {
			return rangeCheckAndOrderFields(fields, inLength-1);
		}
	}
814385
@SuppressWarnings({"unchecked", "rawtypes"})
  public void setField(final FieldDescriptorType descriptor,
                       Object value) {
    if (descriptor.isRepeated()) {
      if (!(value instanceof List)) {
        throw new IllegalArgumentException(
          "Wrong object type used with protocol message reflection.");
      }

      // Wrap the contents in a new list so that the caller cannot change
      // the list's contents after setting it.
      final List newList = new ArrayList();
      newList.addAll((List) value);
      for (final Object element : newList) {
        verifyType(descriptor.getLiteType(), element);
      }
      value = newList;
    } else {
      verifyType(descriptor.getLiteType(), value);
    }

    if (value instanceof LazyField) {
      hasLazyField = true;
    }
    fields.put(descriptor, value);
  }
1218743
private static void generateProtobufDefinedForField(StringBuilder code, FieldElement field, Set<String> enumNames) {
        code.append("@").append(Protobuf.class.getSimpleName()).append("(");

        String fieldType = fieldTypeMapping.get(getTypeName(field));
        if (fieldType == null) {
            if (enumNames.contains(getTypeName(field))) {
                fieldType = "FieldType.ENUM";
            } else {
                if (field.type().kind() == DataType.Kind.MAP) {
                    fieldType = "FieldType.MAP";
                } else {
                    fieldType = "FieldType.OBJECT";
                }

            }
        }

        code.append("fieldType=").append(fieldType);
        code.append(", order=").append(field.tag());
        if (FieldElement.Label.OPTIONAL == field.label()) {
            code.append(", required=false");
        } else if (Label.REQUIRED == field.label()) {
            code.append(", required=true");
        }
        code.append(")\n");

    }
590653
public static MethodHandle ofSetter(FieldDescription.InDefinedShape fieldDescription) {
            return new MethodHandle(HandleType.ofSetter(fieldDescription),
                    fieldDescription.getDeclaringType().asErasure(),
                    fieldDescription.getInternalName(),
                    TypeDescription.VOID,
                    Collections.singletonList(fieldDescription.getType().asErasure()));
        }
947026
public static void generateFieldParser(BindTypeContext context, PersistType persistType, BindProperty property, Modifier... modifiers) {
		Converter<String, String> format = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL);

		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("parse" + format.convert(property.getName())).addJavadoc("for attribute $L parsing\n", property.getName()).returns(typeName(property.getElement()));
		methodBuilder.addModifiers(modifiers);

		switch (persistType) {
		case STRING:
			methodBuilder.addParameter(ParameterSpec.builder(className(String.class), "input").build());
			break;
		case BYTE:
			methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(Byte.TYPE), "input").build());
			break;
		}

		// if property type is byte[], return directly the value
		if (ArrayTypeName.of(Byte.TYPE).equals(property.getPropertyType().getTypeName()) && persistType == PersistType.BYTE) {
			methodBuilder.addStatement("return input");
		} else {

			methodBuilder.beginControlFlow("if (input==null)");
			methodBuilder.addStatement("return null");
			methodBuilder.endControlFlow();

			methodBuilder.addStatement("$T context=$T.jsonBind()", KriptonJsonContext.class, KriptonBinder.class);

			methodBuilder.beginControlFlow("try ($T wrapper=context.createParser(input))", JacksonWrapperParser.class);
			methodBuilder.addStatement("$T jacksonParser=wrapper.jacksonParser", JsonParser.class);

			methodBuilder.addCode("// START_OBJECT\n");
			methodBuilder.addStatement("jacksonParser.nextToken()");

			if (!property.isBindedObject()) {
				methodBuilder.addCode("// value of \"element\"\n");
				methodBuilder.addStatement("jacksonParser.nextValue()");
			}

			String parserName = "jacksonParser";
			BindTransform bindTransform = BindTransformer.lookup(property);

			if (property.getParent()==null || ((ModelClass<?>)property.getParent()).isMutablePojo()) {
				methodBuilder.addStatement("$T result=null", property.getPropertyType().getTypeName());
			} else {
				methodBuilder.addStatement("$T $L=null", property.getPropertyType().getTypeName(), ImmutableUtility.IMMUTABLE_PREFIX+property.getName());	
			}
			
			bindTransform.generateParseOnJackson(context, methodBuilder, parserName, null, "result", property);

			if (property.getParent()==null || ((ModelClass<?>)property.getParent()).isMutablePojo()) {
				methodBuilder.addStatement("return result");				
			} else {
				methodBuilder.addStatement("return $L", ImmutableUtility.IMMUTABLE_PREFIX+property.getName());				
			}

			methodBuilder.nextControlFlow("catch($T e)", Exception.class);
			methodBuilder.addStatement("throw(new $T(e.getMessage()))", KriptonRuntimeException.class);
			methodBuilder.endControlFlow();
		}

		context.builder.addMethod(methodBuilder.build());

	}
769755
public static void setFieldValeByType(Field field, Object obj, String value)
            throws Exception {

        Class<?> type = field.getType();

        String typeName = type.getName();

        if (typeName.equals("int")) {

            if (value.equals("")) {
                value = "0";
            }
            field.set(obj, Integer.valueOf(value));

        } else if (typeName.equals("long")) {

            if (value.equals("")) {
                value = "0";
            }
            field.set(obj, Long.valueOf(value));

        } else if (typeName.equals("boolean")) {

            if (value.equals("")) {
                value = "false";
            }
            field.set(obj, Boolean.valueOf(value));

        } else if (typeName.equals("double")) {

            if (value.equals("")) {
                value = "0.0";
            }
            field.set(obj, Double.valueOf(value));

        } else {

            field.set(obj, value);
        }
    }
1220781
async def field(self, elem=None, elem_type=None, params=None):
        
        elem_type = elem_type if elem_type else elem.__class__
        fvalue = None

        etype = self._get_type(elem_type)
        if self._is_type(etype, UVarintType):
            fvalue = await self.uvarint(get_elem(elem))

        elif self._is_type(etype, IntType):
            fvalue = await self.uint(
                elem=get_elem(elem), elem_type=elem_type, params=params
            )

        elif self._is_type(etype, BlobType):
            fvalue = await self.blob(
                elem=get_elem(elem), elem_type=elem_type, params=params
            )

        elif self._is_type(etype, UnicodeType):
            fvalue = await self.unicode_type(get_elem(elem))

        elif self._is_type(etype, VariantType):
            fvalue = await self.variant(
                elem=get_elem(elem), elem_type=elem_type, params=params
            )

        elif self._is_type(etype, ContainerType):  # container ~ simple list
            fvalue = await self.container(
                container=get_elem(elem), container_type=elem_type, params=params
            )

        elif self._is_type(etype, TupleType):  # tuple ~ simple list
            fvalue = await self.tuple(
                elem=get_elem(elem), elem_type=elem_type, params=params
            )

        elif self._is_type(etype, MessageType):
            fvalue = await self.message(get_elem(elem), msg_type=elem_type)

        else:
            raise TypeError(
                "unknown type: %s %s %s" % (elem_type, type(elem_type), elem)
            )

        return fvalue if self.writing else set_elem(elem, fvalue)
613848
public static Class<?> getParameterTypeOfRepeatedField(Field field) {
    Class<?> componentType = null;
    if (isCollection(field.getType())) {
      validateCollection(field);
      Type parameterType = getParameterType((ParameterizedType) field.getGenericType());
      validateNestedParameterizedType(parameterType);
      componentType = (Class<?>) parameterType;
    } else if (field.getType().isArray()) {
      componentType = field.getType().getComponentType();
      return componentType;
    } else {
      throw new IllegalArgumentException("Unsupported repeated type " + field.getType()
          + " Allowed repeated fields are Collection<T> and arrays");
    }
    validateNestedRepeatedType(componentType, field);
    return componentType;
  }
740707
public void defineConstantField(int modifier, String fieldName, int constant)
    {
        DeclaredType dt = (DeclaredType)asType();
        VariableBuilder builder = new VariableBuilder(this, fieldName, dt.getTypeArguments(), typeParameterMap);
        builder.addModifiers(modifier);
        builder.addModifier(Modifier.STATIC);
        builder.setType(Typ.IntA);
        FieldInfo fieldInfo = new FieldInfo(this, builder.getVariableElement(), new ConstantValue(this, constant));
        addFieldInfo(fieldInfo);
        fieldInfo.readyToWrite();
    }
475552
private static Object generateValue(Field field) {
    Class<?> rawType = field.getType();

    //TODO Objects other than Lists might need parametrized types.
    if (List.class.isAssignableFrom(rawType)) {
      ParameterizedType genericType = (ParameterizedType) field.getGenericType();
      return createListObject(genericType);
    }

    return generateValue(rawType);
  }
1304891
def get_field_def(
    schema: GraphQLSchema, parent_type: GraphQLType, field_node: FieldNode
) -> Optional[GraphQLField]:
    
    name = field_node.name.value
    if name == "__schema" and schema.query_type is parent_type:
        return SchemaMetaFieldDef
    if name == "__type" and schema.query_type is parent_type:
        return TypeMetaFieldDef
    if name == "__typename" and is_composite_type(parent_type):
        return TypeNameMetaFieldDef
    if is_object_type(parent_type) or is_interface_type(parent_type):
        parent_type = cast(Union[GraphQLObjectType, GraphQLInterfaceType], parent_type)
        return parent_type.fields.get(name)
    return None
457319
Optional<ExecutableElement> findGetterMethodFor(Element field) {
        String getterName = getterNameFor(field);
        // FIXME refine this to discover one of possible overloaded methods with correct signature (i.e. single arg of field type)
        TypeElement typeElement = classElementFor(field);
        if (typeElement == null) {
            return Optional.empty();
        }

        List<? extends Element> elements = typeElement.getEnclosedElements();
        List<ExecutableElement> methods = ElementFilter.methodsIn(elements);
        return methods.stream()
                .filter(method -> {
                    String methodName = method.getSimpleName().toString();
                    if (getterName.equals(methodName)) {
                        Set<Modifier> modifiers = method.getModifiers();
                        return
                                // it's not static
                                !modifiers.contains(STATIC)
                                        // it's either public or package visibility
                                        && modifiers.contains(PUBLIC)
                                        || !(modifiers.contains(PRIVATE) || modifiers.contains(PROTECTED));
                    }
                    return false;
                })
                .findFirst();
    }
488011
public static void setFieldIfPossible(Class type, String name, Object value) {
        Optional<Field> declaredField = findDeclaredField(type, name);
        if (declaredField.isPresent()) {
            Field field = declaredField.get();
            Optional<?> converted = ConversionService.SHARED.convert(value, field.getType());
            if (converted.isPresent()) {
                field.setAccessible(true);
                try {
                    field.set(type, converted.get());
                } catch (IllegalAccessException e) {
                    // ignore
                }
            } else {
                field.setAccessible(true);
                try {
                    field.set(type, null);
                } catch (IllegalAccessException e) {
                    // ignore
                }
            }
        }
    }
854700
private boolean isValidPojoField(Field f, Class<?> clazz, ArrayList<Type> typeHierarchy) {
		if(Modifier.isPublic(f.getModifiers())) {
			return true;
		} else {
			boolean hasGetter = false, hasSetter = false;
			final String fieldNameLow = f.getName().toLowerCase().replaceAll("_", "");

			Type fieldType = f.getGenericType();
			Class<?> fieldTypeWrapper = ClassUtils.primitiveToWrapper(f.getType());

			TypeVariable<?> fieldTypeGeneric = null;
			if(fieldType instanceof TypeVariable) {
				fieldTypeGeneric = (TypeVariable<?>) fieldType;
				fieldType = materializeTypeVariable(typeHierarchy, (TypeVariable<?>)fieldType);
			}
			for(Method m : clazz.getMethods()) {
				final String methodNameLow = m.getName().endsWith("_$eq") ?
						m.getName().toLowerCase().replaceAll("_", "").replaceFirst("\\$eq$", "_\\$eq") :
						m.getName().toLowerCase().replaceAll("_", "");

				// check for getter
				if(	// The name should be "get<FieldName>" or "<fieldName>" (for scala) or "is<fieldName>" for boolean fields.
					(methodNameLow.equals("get"+fieldNameLow) || methodNameLow.equals("is"+fieldNameLow) || methodNameLow.equals(fieldNameLow)) &&
					// no arguments for the getter
					m.getParameterTypes().length == 0 &&
					// return type is same as field type (or the generic variant of it)
					(m.getGenericReturnType().equals( fieldType ) || (fieldTypeWrapper != null && m.getReturnType().equals( fieldTypeWrapper )) || (fieldTypeGeneric != null && m.getGenericReturnType().equals(fieldTypeGeneric)) )
				) {
					hasGetter = true;
				}
				// check for setters (<FieldName>_$eq for scala)
				if((methodNameLow.equals("set"+fieldNameLow) || methodNameLow.equals(fieldNameLow+"_$eq")) &&
					m.getParameterTypes().length == 1 && // one parameter of the field's type
					(m.getGenericParameterTypes()[0].equals( fieldType ) || (fieldTypeWrapper != null && m.getParameterTypes()[0].equals( fieldTypeWrapper )) || (fieldTypeGeneric != null && m.getGenericParameterTypes()[0].equals(fieldTypeGeneric) ) )&&
					// return type is void.
					m.getReturnType().equals(Void.TYPE)
				) {
					hasSetter = true;
				}
			}
			if(hasGetter && hasSetter) {
				return true;
			} else {
				if(!hasGetter) {
					LOG.info(clazz+" does not contain a getter for field "+f.getName() );
				}
				if(!hasSetter) {
					LOG.info(clazz+" does not contain a setter for field "+f.getName() );
				}
				return false;
			}
		}
	}
550479
public static Method getSetter(String fieldName, Class<?> clazz, Class<?> fieldType) {
    String setterName = buildSetterName(fieldName);
    try {
      // Using getMathods(), getMathod(...) expects exact parameter type
      // matching and ignores inheritance-tree.
      Method[] methods = clazz.getMethods();
      for(Method method : methods) {
        if(method.getName().equals(setterName)) {
          Class<?>[] paramTypes = method.getParameterTypes();
          if(paramTypes != null && paramTypes.length == 1 && paramTypes[0].isAssignableFrom(fieldType)) {
            return method;
          }
        }
      }
      return null;
    }
    catch (SecurityException e) {
      throw LOG.unableToAccessMethod(setterName, clazz.getName());
    }
  }
722122
private TableFieldSchema getSchemaOfRepeatedFields(Field field) {
    Class<?> parameterType = BigQueryFieldUtil.getParameterTypeOfRepeatedField(field);
    TableFieldSchema tf = parseFieldAnnotations(field);
    tf.setMode(BigQueryFieldMode.REPEATED.getValue());
    if (BigqueryFieldMarshallers.getMarshaller(parameterType) != null) {
      return tf.setType(BigQueryDataTypeUtil.getBigQueryType(
          BigqueryFieldMarshallers.getMarshaller(parameterType).getSchemaType()));
    }
    tf.setType(BigQueryConstants.RECORD_TYPE);
    return tf.setFields(getSchema(parameterType));
  }