Convert a simple value object to specific type. e.g. Long to int, String to LocalDate.

@param genericType Object type: int.class, String.class, Float.class, etc.
@param element Value object.
@return Converted object.
426808
Object toSimpleValue(Class<?> genericType, Object element, TypeAdapters typeAdapters) {
        if (element == null) {
            return null;
        }
        log.info("Convert from " + element.getClass().getName() + " to " + genericType.getName());
        if (genericType.isEnum() && (element instanceof String)) {
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Enum<?> enumValue = Enum.valueOf((Class<? extends Enum>) genericType, (String) element);
            return enumValue;
        }
        Converter converter = SIMPLE_VALUE_CONVERTERS.get(genericType.getName());
        if (converter != null) {
            return converter.convert(element);
        }
        if ((element instanceof String) && (typeAdapters != null)) {
            TypeAdapter<?> adapter = typeAdapters.getTypeAdapter(genericType);
            if (adapter != null) {
                return adapter.deserialize((String) element);
            }
        }
        return element;
    }
60461
@SuppressWarnings("unchecked")
    public static <T> T convertValue(Object target, Class<T> clazz) {
        if (clazz == null) {
            throw new NullPointerException("Class parameter is null!");
        }
        if (target == null) {
            return null;
        }
        if (target instanceof JsonNode) {
            return convertValue((JsonNode) target, clazz);
        }
        if (Number.class.isAssignableFrom(clazz) || byte.class == clazz || short.class == clazz
                || int.class == clazz || long.class == clazz || float.class == clazz
                || double.class == clazz) {
            return convertNumber(target, clazz);
        }
        if (clazz == Boolean.class || clazz == boolean.class) {
            return (T) convertBoolean(target);
        }
        if (clazz == Character.class || clazz == char.class) {
            return (T) convertChar(target);
        }
        if (Date.class.isAssignableFrom(clazz)) {
            return (T) convertDate(target);
        }
        if (Object[].class.isAssignableFrom(clazz) || List.class.isAssignableFrom(clazz)) {
            return (T) convertArrayOrList(target);
        }
        if (clazz.isAssignableFrom(target.getClass())) {
            return (T) target;
        }
        if (clazz == String.class) {
            return (T) target.toString();
        }
        throw new IllegalArgumentException(
                "Cannot convert an object of type [" + target.getClass() + "] to [" + clazz + "]!");
    }
322805
@Override
    public <T extends Number> T numberValue(Class<T> numberType) {
        return ConvertNumberValue.of(numberType, number);
    }
189522
public TypeElement getGenericType(TypeMirror typeMirror) {
        return typeMirror.accept(new SimpleTypeVisitor6<TypeElement, Void>() {
            @Override
            public TypeElement visitDeclared(DeclaredType declaredType, Void v) {
                TypeElement genericTypeElement = null;
                TypeElement typeElement = (TypeElement) declaredType.asElement();
                if (parcelClass != null && typeUtils.isAssignable(typeElement.asType(), listTypeMirror)) {
                    List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments();
                    if (!typeArguments.isEmpty()) {
                        for (TypeMirror genericType : typeArguments) {
                            if (genericType instanceof WildcardType) {
                                WildcardType wildcardType = (WildcardType) genericType;
                                TypeMirror extendsType = wildcardType.getExtendsBound();
                                if (extendsType != null) {
                                    typeElement = elementUtils.getTypeElement(extendsType.toString());
                                    if (typeElement.getAnnotation(parcelClass) != null) {
                                        genericTypeElement = typeElement;
                                        break;
                                    }

                                }
                            } else {
                                typeElement = elementUtils.getTypeElement(genericType.toString());
                                if (typeElement.getAnnotation(parcelClass) != null) {
                                    genericTypeElement = typeElement;
                                    break;
                                }
                            }
                        }
                    }
                }
                return genericTypeElement;
            }
        }, null);
    }
560003
@SuppressWarnings("unchecked")
	private <T> T convertSpecial(Type type, Class<T> rowType, Object value, T defaultValue) {
		if (null == rowType) {
			return null;
		}

		// 集合转换（不可以默认强转）
		if (Collection.class.isAssignableFrom(rowType)) {
			final CollectionConverter collectionConverter = new CollectionConverter(type);
			return (T) collectionConverter.convert(value, (Collection<?>) defaultValue);
		}

		// Map类型（不可以默认强转）
		if (Map.class.isAssignableFrom(rowType)) {
			final MapConverter mapConverter = new MapConverter(type);
			return (T) mapConverter.convert(value, (Map<?, ?>) defaultValue);
		}

		// 默认强转
		if (rowType.isInstance(value)) {
			return (T) value;
		}

		// 数组转换
		if (rowType.isArray()) {
			final ArrayConverter arrayConverter = new ArrayConverter(rowType);
			try {
				return (T) arrayConverter.convert(value, defaultValue);
			} catch (Exception e) {
				// 数组转换失败进行下一步
			}
		}

		// 枚举转换
		if (rowType.isEnum()) {
			return (T) new EnumConverter(rowType).convert(value, defaultValue);
		}

		// 表示非需要特殊转换的对象
		return null;
	}
188323
public static <E> GenericData getDataModelForType(Class<E> type) {
    // Need to check if SpecificRecord first because specific records also
    // implement GenericRecord
    if (SpecificRecord.class.isAssignableFrom(type)) {
      return new SpecificData(type.getClassLoader());
    } else if (IndexedRecord.class.isAssignableFrom(type)) {
      return GenericData.get();
    } else {
      return AllowNulls.get();
    }
  }
980958
public final Object convertValue(Object value, IType intrType)
  {
    //==================================================================================
    // Null handling
    //==================================================================================
    if( intrType == null )
    {
      return null;
    }

    //## todo: This is a horrible hack
    //## todo: The only known case where this is necessary is when we have an array of parameterized java type e.g., List<String>[]
    intrType = getBoundingTypeOfTypeVariable( intrType );

    if( value == null )
    {
      return intrType.isPrimitive() ? convertNullAsPrimitive( intrType, true ) : null;
    }

    IType runtimeType = TypeSystem.getFromObject( value );

    //==================================================================================
    // IPlaceholder type handling
    //==================================================================================
    if( (intrType instanceof IPlaceholder && ((IPlaceholder)intrType).isPlaceholder()) ||
        (runtimeType instanceof IPlaceholder && ((IPlaceholder)runtimeType).isPlaceholder()) )
    {
      return value;
    }

    //==================================================================================
    // Runtime polymorphism (with java array semantics)
    //==================================================================================
    if( intrType == runtimeType )
    {
      return value;
    }
    if( intrType.equals( runtimeType ) )
    {
      return value;
    }
    if( intrType.isAssignableFrom( runtimeType ) )
    {
      value = extractObjectArray( intrType, value );
      return value;
    }
    if( intrType.isArray() && runtimeType.isArray() )
    {
      if( intrType.getComponentType().isAssignableFrom( runtimeType.getComponentType() ) )
      {
        value = extractObjectArray( intrType, value );
        return value;
      }
      else if( intrType instanceof IGosuArrayClass &&
               value instanceof IGosuObject[] )
      {
        return value;
      }
    }
    // Proxy coercion. The proxy class generated for Java classes is not a super type of the Gosu class.
    // The following check allows coercion of the Gosu class to the Gosu proxy class needed for the super call.
    if( intrType instanceof IJavaType &&
        IGosuClass.ProxyUtil.isProxy( intrType ) &&
        runtimeType instanceof IGosuClass &&
        intrType.getSupertype() != null &&
        intrType.getSupertype().isAssignableFrom( runtimeType ) )
    {
      return value;
    }

    // Check Java world types
    //noinspection deprecation,unchecked
    if( intrType instanceof IJavaType &&
        ((IJavaType)intrType).getIntrinsicClass().isAssignableFrom( value.getClass() ) )
    {
      return value;
    }

    // casts to structs are dynamic, pass value through unchanged
    if( intrType instanceof IGosuClass && ((IGosuClass)intrType).isStructure() )
    {
      return value;
    }

    //==================================================================================
    // Coercion
    //==================================================================================
    Object convertedValue = coerce( intrType, runtimeType, value );
    if( convertedValue != null )
    {
      return convertedValue;
    }
    else
    {
      //If the null arose from an actual coercion, return it
      if( canCoerce( intrType, runtimeType ) )
      {
        return convertedValue;
      }
      else
      {
        //otherwise, return the value itself uncoerced (See comment above)
        if( !runtimeType.isArray() )
        {
          return NO_DICE;
        }
        return value;
      }
    }
  }
480094
public TypeMirror getType(Element element) {
    return elementTypeMap.containsKey(element) ? elementTypeMap.get(element) : element.asType();
  }
51352
public <T> Object convert(Class collectionType, Class<T> elementType, String origin) throws ConversionException {
        Converter<T> elementConverter = find(elementType);
        CollectionConverter<T> converter = new CollectionConverter<>(elementConverter, stringSplitter);

        try {
            Collection<T> converted = converter.convert(origin);
            return castCollectionToType(collectionType, converted);
        } catch (Exception e) {
            throw new ConversionException(String.format("Could not convert string <%s> to collection <%s> " +
                    "with element type <%s>", origin, collectionType, elementType), e);
        }
    }
1312721
protected Class<?> getValueType(AnnotatedElement element) {
        if (element instanceof Field) {
            return ((Field) element).getType();
        }
        if (element instanceof Method) {
            return ((Method) element).getReturnType();
        }
        throw new PropertyLoaderException("Could not get element type");
    }
61890
public static Class<Object> loadValidInputTypes(String javaType, String type) {
        // we have generics in the javatype, if so remove it so its loadable from a classloader
        int idx = javaType.indexOf('<');
        if (idx > 0) {
            javaType = javaType.substring(0, idx);
        }

        try {
            Class<Object> clazz = getPrimitiveWrapperClassType(type);
            if (clazz == null) {
                clazz = loadPrimitiveWrapperType(javaType);
            }
            if (clazz == null) {
                clazz = loadStringSupportedType(javaType);
            }
            if (clazz == null) {
                try {
                    clazz = (Class<Object>) Class.forName(javaType);
                } catch (Throwable e) {
                    // its a custom java type so use String as the input type, so you can refer to it using # lookup
                    if ("object".equals(type)) {
                        clazz = loadPrimitiveWrapperType("java.lang.String");
                    }
                }
            }

            // favor specialized UI for these types
            if (clazz != null && (clazz.equals(String.class) || clazz.equals(Date.class) || clazz.equals(Boolean.class)
                    || clazz.isPrimitive() || Number.class.isAssignableFrom(clazz))) {
                return clazz;
            }

            // its a custom java type so use String as the input type, so you can refer to it using # lookup
            if ("object".equals(type)) {
                clazz = loadPrimitiveWrapperType("java.lang.String");
                return clazz;
            }

        } catch (Throwable e) {
            // ignore errors
        }
        return null;
    }
1316726
@SuppressWarnings("unchecked")
	public <T> T convertElement(ConversionContext context, Object source,
			TypeReference<T> destinationType) throws ConverterException {
		return (T) elementConverter.convert(context, source, destinationType);
	}
662466
protected static Object convertBasicValue(String value, Class<?> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type cannot be null");
        }

        if (String.class.equals(type)) {
            return value;
        }

        if (value == null || value.trim().isEmpty()) {
            return null;
        }

        try {
            value = value.trim();
            if (Byte.class.equals(type)) {
                return Byte.parseByte(value);
            } else if (Short.class.equals(type)) {
                return Short.parseShort(value);
            } else if (Integer.class.equals(type)) {
                return Integer.parseInt(value);
            } else if (Long.class.equals(type)) {
                return Long.parseLong(value);
            } else if (BigInteger.class.equals(type)) {
                return new BigInteger(value);
            } else if (Float.class.equals(type)) {
                return Float.parseFloat(value);
            } else if (Double.class.equals(type)) {
                return Double.parseDouble(value);
            } else if (BigDecimal.class.equals(type)) {
                return new BigDecimal(value);
            } else if (Boolean.class.equals(type)) {
                return Boolean.parseBoolean(value);
            }
        } catch (Exception e) {
            throw new UniformException(String.format("Error while converting value %s to data type %s. Make sure the element has correct values and/or validators", value, type.getName()), e);
        }

        throw new UnsupportedOperationException("Could not convert value to unknown type: " + type.getName());
    }
204356
def _cast_to_type(self, value):
        
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            value = datetime.datetime(value.year, value.month, value.day)
            return value
        try:
            value = date_parser(value)
            return value
        except ValueError:
            self.fail('invalid', value=value)
1196021
@Override
    public GenericsContext type(final Class<?> type) {
        return type == currentType ? this : new GenericsContext(genericsInfo, type, root);
    }
1020766
public static <T> T convert(Type type, Object value, T defaultValue) throws ConvertException {
		return ConverterRegistry.getInstance().convert(type, value, defaultValue);
	}
1287328
@SuppressWarnings("unchecked")
	public static <T> T cast(Object obj, Class<T> type){
		if(obj == null){
			return null;
		}
		if(obj.getClass() == type){
			return (T) obj;
		}
		if(isNativeNumberType(obj.getClass()) && isNativeNumberType(type)){
			return castToNativeNumber((Number)obj, type);
		}
		return type.cast(obj);
	}