Convert value via expected class type.

@param value original value
@param convertType expected class type
@return converted value
482595
public static Object convertValue(final Object value, final Class<?> convertType) {
        if (null == value) {
            return convertNullValue(convertType);
        } 
        if (value.getClass() == convertType) {
            return value;
        }
        if (value instanceof Number) {
            return convertNumberValue(value, convertType);
        }
        if (value instanceof Date) {
            return convertDateValue(value, convertType);
        }
        if (String.class.equals(convertType)) {
            return value.toString();
        } else {
            return value;
        }
    }
142522
@SuppressWarnings("rawtypes")
	@Override
	protected Object convertToType(Class type, Object value) throws Throwable {
		String[] strings = value.toString().split(",");
		
		if (strings.length != 2) {
			throw new ConversionException(
					"GeoPt 'value' must be able to be splitted into 2 float values "
							+ "by ',' (latitude,longitude)");
		}
		
		try {
			float latitude = new BigDecimal(strings[0].trim()).floatValue();
			float longitude = new BigDecimal(strings[1].trim()).floatValue();
			return new GeoPt(latitude, longitude);
		} catch (Exception e) {
			throw new ConversionException(
					"Cannot parse GeoPt value into 2 float values: "
							+ "latitude [" + strings[0].trim()
							+ "], longitude [" + strings[1].trim() + "]");
		}
	}
149648
private BigDecimal convertValue(final Object value) {
		if (value == null) {
			return null;
		} else if (value instanceof BigDecimal) {
			return (BigDecimal) value;
		}

		// Try and convert "String" value
		String dataString = value.toString();
		if (Util.empty(dataString)) {
			return null;
		}

		try {
			return new BigDecimal(dataString);
		} catch (NumberFormatException ex) {
			throw new SystemException(
					"Could not convert data of type " + value.getClass() + " with String value "
					+ dataString + " to BigDecimal", ex);
		}
	}
707642
public static <T> Conversion<T> to(final Class<T> type) {

		/**
		 * Proxies type conversion to allow for the fact that the value may
		 * provide its own conversion and other subtleties. The goal is to
		 * preserve the identical behavior as if {@link #asType(Class,Object)}
		 * were called.
		 *
		 */
		return new Conversion<T>() {

			@Override
			public Object[] getTypeKeys() {
				Conversion<?> conversion=typeConversions.get(type);
				return (conversion!=null)
					? TypeConverter.getTypeKeys(conversion)
						.toArray(new Object[0])
					: new Object[0];
			}

			@Override
			public T convert(Object value) {
				return TypeConverter.convert(type,value);
			}
		};
	}
215512
def convert(self, value, _type):
        
        return self.type_convertors.get(_type, lambda x: x)(value)
160882
public static final boolean valueIsNotDefault(FieldType type, Object value)
   {
      boolean result = true;

      if (value == null)
      {
         result = false;
      }
      else
      {
         DataType dataType = type.getDataType();
         switch (dataType)
         {
            case BOOLEAN:
            {
               result = ((Boolean) value).booleanValue();
               break;
            }

            case CURRENCY:
            case NUMERIC:
            {
               result = !NumberHelper.equals(((Number) value).doubleValue(), 0.0, 0.00001);
               break;
            }

            case DURATION:
            {
               result = (((Duration) value).getDuration() != 0);
               break;
            }

            default:
            {
               break;
            }
         }
      }

      return result;
   }
1303210
@SuppressWarnings({ "unchecked", "rawtypes" })
    public static Object convert(Object source, Class<?> target) throws ConversionException {
        if (target == null) {
            throw new ConversionException("Unable to perform conversion, target was null");
        }
        if (source == null) {
            if (target.isPrimitive()) {
                throw new ConversionException(String.format("Unable to convert null to primitive value of %s", target));
            }
            return source;
        } else if ((source instanceof Float && ((Float) source).isNaN()) || (source instanceof Double && ((Double) source).isNaN())) {
            // Don't convert NaN values
            return source;
        }
        //		if (BaseConnection.class.isAssignableFrom(source.getClass()) && !target.equals(IConnection.class)) {
        //			log.debug("Conversion failure - source: {} target: {}", source.getClass(), target);
        //			throw new ConversionException("Source is not assignable and target is not equal to IConnection");
        //		}
        if (target.isInstance(source)) {
            return source;
        }
        if (target.isAssignableFrom(source.getClass())) {
            return source;
        }
        if (target.isArray()) {
            return convertToArray(source, target);
        }
        if (target.equals(String.class)) {
            return source.toString();
        }
        if (target.isPrimitive()) {
            return convertToWrappedPrimitive(source, primitiveMap.get(target));
        }
        if (wrapperMap.containsKey(target)) {
            return convertToWrappedPrimitive(source, target);
        }
        if (target.equals(Map.class)) {
            return convertBeanToMap(source);
        }
        if (target.equals(List.class) || target.equals(Collection.class)) {
            if (source.getClass().equals(LinkedHashMap.class)) {
                return convertMapToList((LinkedHashMap<?, ?>) source);
            } else if (source.getClass().isArray()) {
                return convertArrayToList((Object[]) source);
            }
        }
        if (target.equals(Set.class) && source.getClass().isArray()) {
            return convertArrayToSet((Object[]) source);
        }
        if (target.equals(Set.class) && source instanceof List) {
            return new HashSet((List) source);
        }
        if (source instanceof Map) {
            return convertMapToBean((Map) source, target);
        }
        throw new ConversionException(String.format("Unable to preform conversion from %s to %s", source, target));
    }
1081345
@Override
    public byte[] convertTo(final Object value) {
        if (value == null) {
            final BsonWriter out = writerPool.get().tiny(tiny);
            out.writeNull();
            byte[] result = out.toArray();
            writerPool.accept(out);
            return result;
        }
        return convertTo(value.getClass(), value);
    }
550577
public static Object convertToClass(String value, Class<?> clazz) {
    Object propertyValue;
    if (clazz.isAssignableFrom(int.class)) {
      propertyValue = Integer.parseInt(value);
    }
    else if (clazz.isAssignableFrom(long.class)) {
      propertyValue = Long.parseLong(value);
    }
    else if (clazz.isAssignableFrom(float.class)) {
      propertyValue = Float.parseFloat(value);
    }
    else if (clazz.isAssignableFrom(boolean.class)) {
      propertyValue = Boolean.parseBoolean(value);
    } else {
      propertyValue = value;
    }
    return propertyValue;
  }
168117
private Object convert(Object value, String type) {
        if (EnumRuleType.STRING.equals(type)) {
            if (!(value instanceof String)) {
                return String.valueOf(value);
            }
        } else if (EnumRuleType.DOUBLE.equals(type)) {
            if (!(value instanceof Double)) {
                if (value instanceof Number) {
                    return NumberUtils.convertNumberToTargetClass((Number) value, Double.class);
                } else {
                    return NumberUtils.parseNumber(value.toString(), Double.class);
                }
            }
        } else if (EnumRuleType.INTEGER.equals(type)) {
            if (!(value instanceof Integer)) {
                if (value instanceof Number) {
                    return NumberUtils.convertNumberToTargetClass((Number) value, Integer.class);
                } else {
                    return NumberUtils.parseNumber(value.toString(), Integer.class);
                }
            }
        }
        return value;
    }
1009831
public <T> T convert(String value, Class<T> to) {
        if (Strings.isEmpty(value) && !(String.class.equals(to) || String[].class.equals(to))) {
            return null;
        }

        if (String.class.equals(to)) {
            return to.cast(value);
        } else if (Integer.class.equals(to)) {
            return to.cast(Integer.valueOf(value));
        } else if (Double.class.equals(to)) {
            return to.cast(Double.valueOf(value));
        } else if (Long.class.equals(to)) {
            return to.cast(Long.valueOf(value));
        } else if (Boolean.class.equals(to)) {
            return to.cast(Boolean.valueOf(value));
        } else if (URL.class.equals(to)) {
            try {
                return to.cast(new URI(value).toURL());
            } catch (MalformedURLException e) {
                throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
            }
        } else if (URI.class.equals(to)) {
            try {
                return to.cast(new URI(value));
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("Unable to convert value " + value + " to URL", e);
            }
        } else {
            String trimmedValue = extractEnumName(value);
            if (to.isEnum()) {
                return (T) Enum.valueOf((Class<Enum>) to, trimmedValue.toUpperCase());
            } else if (String[].class.equals(to)) {
                final String[] convertedArray = value.split(",");
                if (convertedArray.length == 0) {
                    return to.cast(new String[0]);
                }

                trimElements(convertedArray);

                if (convertedArray.length == 1 && hasOnlyBlanks(convertedArray)) {
                    return to.cast(new String[0]);
                }

                return to.cast(convertedArray);
            } else if (Charset.class.equals(to)) {
                return to.cast(Charset.forName(trimmedValue.toUpperCase()));
            } else if (Class.class.equals(to)) {
                try {
                    Object clazz = Class.forName(value);
                    return to.cast(clazz);
                } catch (Exception e) {
                    throw new IllegalArgumentException("Unable to find class [" + value + "].", e);
                }
            } else // Try to create instance via reflection
            {
                try {
                    Object instance = Class.forName(value).newInstance();
                    return to.cast(instance);
                } catch (Exception e) {
                    throw new IllegalArgumentException(
                        "Unable to convert value [" + value + "] to a class [" + to.getName() + "].", e);
                }
            }
        }
    }
1155531
private static Object transformType(Object value) {
    if (value == null) {
      return null;
    }
    String valueString = value.toString();

    // check for boolean
    boolean boolValue = BooleanUtils.toBoolean(valueString);
    if (StringUtils.equals(valueString, Boolean.toString(boolValue))) {
      return boolValue;
    }

    // check for integer
    int intValue = NumberUtils.toInt(valueString);
    if (StringUtils.equals(valueString, Integer.toString(intValue))) {
      return intValue;
    }

    return value;
  }
333745
public <T> T convert(Object value, Class<T> clazz) {
    if (null == value) return null;
    if (value instanceof String && Strings.isEmpty((String) value)) { return null; }
    if (value.getClass().isArray()) {
      Object[] values = (Object[]) value;
      if (values.length >= 1) {
        value = values[0];
      }
    }
    return conversion.convert(value, clazz);
  }
787295
protected function convert ($type, $value)
		{
			switch ($type)
			{
				case 'string':
					return (string) $value;

				case 'number':
					return is_float($value)
						? (float) $value
						: (int) $value;

				case 'boolean':
					return $value === true || $value === 'true' || $value === '1' || $value === 'on';

				default:
					if (is_float($value))
					{
						return $this->convert('number', $value);
					}
					if (is_numeric($value))
					{
						return strpos($value, '.') !== FALSE
							? (float) $value
							: (int) $value;
					}
					if ($value === 'true' || $value === 'false')
					{
						return $value === 'true';
					}
					if ($value === '')
					{
						return null;
					}
			}
			return $value;
		}
51952
public static Converter converterFor( Class type )
    {
        if (!converters.containsKey( type ))
            throw new IllegalArgumentException( "Don't know type: " + type );

        return converters.get( type );
    }
440002
protected function convertType($value)
    {
        switch(true) {

            case is_bool($value):
                return new BoolType;

            case is_int($value):
                return new NumberType(['nativeType'=>'int']);

            case is_float($value):
                return new NumberType(['nativeType'=>'float']);

            case is_null($value):
                return new StringType(['canBeNull'=>true]);

            case $value instanceof DateTime:
                return new TemporalType;

            case $this->isSequence($value):
                return $this->createSequence($value);

            case is_object($value):
                return $this->createObject($value);

            case $this->hasKeysAndValues($value):
                return $this->createArrayType($value);

            default:
                return new StringType;
        }

    }
1122021
public static Object convertToUIInputValue(final ConverterFactory converterFactory,
            final InputComponent<?, ?> input, final Object value)
   {
      final Object result;
      Class<Object> sourceType = (Class<Object>) value.getClass();
      Class<Object> targetType = (Class<Object>) input.getValueType();
      if (!targetType.isAssignableFrom(sourceType))
      {
         if (input instanceof SelectComponent)
         {
            SelectComponent<?, Object> selectComponent = (SelectComponent<?, Object>) input;
            Iterable<Object> valueChoices = selectComponent.getValueChoices();
            final Converter<Object, ?> selectConverter;
            if (String.class.isAssignableFrom(sourceType))
            {
               selectConverter = getItemLabelConverter(converterFactory, selectComponent);
            }
            else
            {
               selectConverter = converterFactory.getConverter(targetType, sourceType);
            }
            Object chosenObj = null;
            if (valueChoices != null)
            {
               for (Object valueChoice : valueChoices)
               {
                  Object convertedObj = selectConverter.convert(valueChoice);
                  if (convertedObj.equals(value))
                  {
                     chosenObj = valueChoice;
                     break;
                  }
               }
            }
            result = chosenObj;
         }
         else
         {

            Converter<String, Object> valueConverter = (Converter<String, Object>) input.getValueConverter();
            if (valueConverter != null)
            {
               if (value instanceof String)
               {
                  result = valueConverter.convert((String) value);
               }
               else
               {
                  Converter<Object, String> stringConverter = converterFactory.getConverter(sourceType, String.class);
                  CompositeConverter compositeConverter = new CompositeConverter(stringConverter, valueConverter);
                  result = compositeConverter.convert(value);
               }

            }
            else
            {
               Converter<Object, Object> converter = converterFactory.getConverter(sourceType, targetType);
               result = converter.convert(value);
            }
         }
      }
      else
      {

         Converter<String, Object> valueConverter = (Converter<String, Object>) input.getValueConverter();
         if (valueConverter != null && value instanceof String)
         {
            result = valueConverter.convert((String) value);
         }
         else
         {
            // FORGE-2493: By setting the system property 'org.jboss.forge.ui.select_one_lenient_value' to true will
            // allow UISelectOne to set values outside of its value choices. (pre-2.20.0.Final behavior)
            if (input instanceof SelectComponent && !Boolean.getBoolean("org.jboss.forge.ui.select_one_lenient_value"))
            {
               SelectComponent<?, Object> selectComponent = (SelectComponent<?, Object>) input;
               Set<Object> valueChoices = Sets.toSet(selectComponent.getValueChoices());
               // Check if the value is contained in the valueChoices set
               if (valueChoices != null && valueChoices.contains(value))
               {
                  result = value;
               }
               else
               {
                  // equals()/hashCode may not have been implemented. Trying to compare from the String representation
                  Object chosenObj = null;
                  if (valueChoices != null)
                  {
                     Converter<Object, String> selectConverter = getItemLabelConverter(converterFactory,
                              selectComponent);
                     String valueLabel = selectConverter.convert(value);
                     for (Object valueChoice : valueChoices)
                     {
                        String convertedObj = selectConverter.convert(valueChoice);
                        if (convertedObj.equals(valueLabel))
                        {
                           chosenObj = valueChoice;
                           break;
                        }
                     }
                  }
                  result = chosenObj;
               }
            }
            else
            {
               result = value;
            }
         }
      }
      return result;
   }