Cast value object.

@param m        the m
@param castType the cast type
@param value    the value
@return the object
778529
@SuppressWarnings("PMD.LooseCoupling")
    public static Object castValue(Method m, Class<?> castType, String value) {

        try {
            if (castType.isEnum()) {
                Method valueOf;
                try {
                    valueOf = castType.getMethod("valueOf", String.class);
                    return valueOf.invoke(null, value);
                } catch (Exception e) {
                    log.info("enum value of excute error : (" + castType.getName() + ") | " + value);
                    return null;
                }
            } else if (castType == Integer.class || castType == int.class) {
                return Integer.parseInt(value);
            } else if (castType == Long.class || castType == long.class) {
                return Long.parseLong(value);
            } else if (castType == Double.class || castType == double.class) {
                return Double.parseDouble(value);
            } else if (castType == Boolean.class || castType == boolean.class) {
                return Boolean.parseBoolean(value);
            } else if (castType == Float.class || castType == float.class) {
                return Float.parseFloat(value);
            } else if (castType == String.class) {
                return value;
            } else if (castType == ArrayList.class || castType == List.class) {
                ParameterizedType paramType = (ParameterizedType) m.getGenericParameterTypes()[0];
                Class<?> paramClass = (Class<?>) paramType.getActualTypeArguments()[0];
                List<Object> castList = new ArrayList<>();
                String[] values = value.split(",");
                for (String v : values) {
                    castList.add(castValue(m, paramClass, v));
                }

                return castList;
            } else {
                log.info("invalid castType : " + castType);
                return null;
            }
        } catch (NumberFormatException e) {
            log.info("value : " + value + " is invalid value, setter parameter type is  : " + castType);
            return null;
        }
    }
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);
	}
573651
function castType(val, type, def) {
    function cast() {
        if (!is_1.isValue(val))
            return to_1.toDefault(null, def);
        // If no type specified try to get automatically.
        type = type || getType(val);
        if (is_1.isArray(type)) {
            return to_1.toArray(val)
                .map(function (v, i) { return castType(v, type[i] || type[i - 1] || type[0]); });
        }
        else if (is_1.isFunction(type)) {
            val = to_1.toArray(val);
            return type.apply(void 0, val);
        }
        else if (is_1.isString(type)) {
            type = type.toLowerCase();
            var func = toMap[type];
            if (func)
                return func(val);
            return to_1.toDefault(null, def);
        }
        else {
            return val;
        }
    }
    return function_1.tryWrap(cast)(def);
}
187225
protected function castToType($value, string $type)
    {
        $platform = $this->connection->getDatabasePlatform();

        return Type::getType($type)->convertToDatabaseValue($value, $platform);
    }
1240466
static <T> T cast(Object obj, Class<T> type) {
        if (type == String.class) {
            if (obj == null)
                obj = "";
            obj = obj.toString();
        } else if (type == BigInteger.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            obj = new BigInteger("" + obj);
        } else if (type == BigDecimal.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            obj = new BigDecimal(("" + obj).replace(",","."));
        } else if (type == Integer.class || type == int.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            if(obj instanceof Integer){

            }else
                obj = new BigDecimal(""+obj).intValue();
        } else if (type == Long.class || type==long.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            if(obj instanceof Long){

            }else
                obj = new BigDecimal(("" + obj).replace(",",".")).longValue();
        } else if (type == Float.class || type==float.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            if(obj instanceof Float){

            }else
                obj = new BigDecimal(("" + obj).replace(",",".")).floatValue();
        } else if (type == Double.class || type==double.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "0";
            if(obj instanceof Double){

            }else
                obj = new BigDecimal(("" + obj).replace(",",".")).doubleValue();
        } else if (type == Boolean.class || type==boolean.class) {
            if (obj == null || (""+obj).isEmpty())
                obj = "false";
            if(obj instanceof Number){
                obj = ((Number) obj).intValue()!=0;
            }else
                obj = Boolean.parseBoolean("" + obj);
        } else if (type == Date.class) {
            if((""+obj).isEmpty())
                obj = null;
            if (obj != null) {
                if (obj instanceof String) {
                    Date dt = null;
                    SimpleDateFormat[] sdf = new SimpleDateFormat[]{
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm"),
                            new SimpleDateFormat("yyyy-MM-dd")
                    };
                    for(SimpleDateFormat s:sdf){
                        try {
                            dt = s.parse("" + obj);
                            break;
                        }catch (Throwable e){}
                    }
                    if(dt==null)
                        dt = new Date(Long.parseLong("" + obj));
                    obj = dt;
                } else if (obj instanceof Long) {
                    obj = new Date((Long) obj);
                }
            }
        } else if(type.isEnum()){
            if(obj != null && obj instanceof String){
                obj = Enum.valueOf((Class<? extends Enum>)type,((String) obj).toUpperCase());
            }
        }

        return (T) obj;
    }
1028147
private static Object castObject(
        Class<?> toType, Class<?> fromType, Object fromValue,
        int operation, boolean checkOnly )
        throws UtilEvalError
    {
        /*
            Lots of preconditions checked here...
            Once things are running smoothly we might comment these out
            (That's what assertions are for).
        */
        if ( checkOnly && fromValue != null )
            throw new InterpreterError("bad cast params 1");
        if ( !checkOnly && fromValue == null )
            throw new InterpreterError("bad cast params 2");
        if ( fromType == Primitive.class )
            throw new InterpreterError("bad from Type, need to unwrap");
        if ( fromValue == Primitive.NULL && fromType != null )
            throw new InterpreterError("inconsistent args 1");
        if ( fromValue == Primitive.VOID && fromType != Void.TYPE )
            throw new InterpreterError("inconsistent args 2");
        if ( toType == Void.TYPE )
            throw new InterpreterError("loose toType should be null");

        // assignment to loose type, void type, or exactly same type
        if ( toType == null || arrayElementType(toType) == arrayElementType(fromType) )
            return checkOnly ? VALID_CAST :
                fromValue;

        if ( null != fromType && fromType.isArray() )
            if ( operation == Types.CAST
                    || isJavaAssignable(Collection.class, toType)
                    || isJavaAssignable(Map.class, toType) )
                return checkOnly ? VALID_CAST : BshArray.castArray(
                        toType, fromType, fromValue );

        // Casting to primitive type
        if ( toType.isPrimitive() )
        {
            if ( fromType == Void.TYPE || fromType == null
                || fromType.isPrimitive() )
            {
                // Both primitives, do primitive cast
                return Primitive.castPrimitive(
                    toType, fromType, (Primitive)fromValue,
                    checkOnly, operation );
            } else
            {
                if ( Primitive.isWrapperType( fromType ) )
                {
                    // wrapper to primitive
                    // Convert value to Primitive and check/cast it.

                    //Object r = checkOnly ? VALID_CAST :
                    Class unboxedFromType = Primitive.unboxType( fromType );
                    Primitive primFromValue;
                    if ( checkOnly )
                        primFromValue = null; // must be null in checkOnly
                    else
                        primFromValue = (Primitive)Primitive.wrap(
                            fromValue, unboxedFromType );

                    return Primitive.castPrimitive(
                        toType, unboxedFromType, primFromValue,
                        checkOnly, operation );
                } else
                {
                    // Cannot cast from arbitrary object to primitive
                    if ( checkOnly )
                        return INVALID_CAST;
                    else
                        throw castError( toType, fromType, operation );
                }
            }
        }

        // Else, casting to reference type

        // Casting from primitive or void (to reference type)
        if ( fromType == Void.TYPE || fromType == null
            || fromType.isPrimitive() )
        {
            // cast from primitive to wrapper type
            if ( Primitive.isWrapperType( toType )
                && fromType != Void.TYPE && fromType != null )
            {
                // primitive to wrapper type
                return checkOnly ? VALID_CAST :
                    Primitive.castWrapper(
                        Primitive.unboxType(toType),
                        ((Primitive)fromValue).getValue() );
            }

            // Primitive (not null or void) to Object.class type
            if ( toType == Object.class
                && fromType != Void.TYPE && fromType != null )
            {
                // box it
                return checkOnly ? VALID_CAST :
                    ((Primitive)fromValue).getValue();
            }

            // Primitive to arbitrary object type.
            // Allow Primitive.castToType() to handle it as well as cases of
            // Primitive.NULL and Primitive.VOID
            return Primitive.castPrimitive(
                toType, fromType, (Primitive)fromValue, checkOnly, operation );
        }

        // If type already assignable no cast necessary
        // We do this last to allow various errors above to be caught.
        // e.g cast Primitive.Void to Object would pass this
        if ( toType.isAssignableFrom( fromType ) )
            return checkOnly ? VALID_CAST :
                fromValue;

        // Can we use the proxy mechanism to cast a bsh.This to
        // the correct interface?
        if ( toType.isInterface()
            && bsh.This.class.isAssignableFrom( fromType )
        )
            return checkOnly ? VALID_CAST :
                ((bsh.This)fromValue).getInterface( toType );

        // Both numeric wrapper types?
        // Try numeric style promotion wrapper cast
        if ( Primitive.isWrapperType( toType )
            && Primitive.isWrapperType( fromType ) )
            return checkOnly ? VALID_CAST :
                Primitive.castWrapper( toType, fromValue );

        if ( checkOnly )
            return INVALID_CAST;
        else
            throw castError( toType, fromType , operation  );
    }
1096521
def cast(self, topic, value):
        
        datatype_key = topic.meta.get('datatype', 'none')
        result = self._datatypes[datatype_key].cast(topic, value)
        validate_dt = topic.meta.get('validate', None)
        if validate_dt:
            result = self._datatypes[validate_dt].cast(topic, result)
        return result
871112
def cast_type(self, var, cast_type=None):
        

        if cast_type is None:
            cast_type = self.valid_values

        try:
            if cast_type == int:
                return int(var)
            elif cast_type == float:
                return float(var)
            elif type == str:
                return str(var)
            elif isinstance(cast_type, list):
                # cast var to be of the same type as those in the list
                return type(cast_type[0])(var)
            else:
                return None
        except ValueError:
            return None

        return var
1014604
@SuppressWarnings("unchecked")
    public static <T> T castToType(final Class<T> type, final Object val) throws DevFailed {

	T result;
	if (val == null) {
	    result = null;
	} else if (type.isAssignableFrom(val.getClass())) {
	    result = (T) val;
	} else {
	    LOGGER.debug("converting {} to {}", val.getClass().getCanonicalName(), type.getCanonicalName());
	    // if input is not an array and we want to convert it to an array.
	    // Put
	    // the value in an array
	    Object array = val;
	    if (!val.getClass().isArray() && type.isArray()) {
		array = Array.newInstance(val.getClass(), 1);
		Array.set(array, 0, val);
	    }
	    final Transmorph transmorph = new Transmorph(creatConv());
	    try {
		result = transmorph.convert(array, type);
	    } catch (final ConverterException e) {
		LOGGER.error("convertion error", e);
		throw DevFailedUtils.newDevFailed(e);
	    }
	}
	return result;
    }
377563
public static Enum castToEnum(Object object, Class<? extends Enum> type) {
        if (object==null) return null;
        if (type.isInstance(object)) return (Enum) object;
        if (object instanceof String || object instanceof GString) {
            return Enum.valueOf(type, object.toString());
        }
        throw new GroovyCastException(object, type);
    }
26102
public function cast($value)
    {
        $fn = 'cast' . ucfirst(gettype($value));
        
        return method_exists($this, $fn) ? $this->$fn($value) : (string)$value;
    }
510823
function convertValue(value, cast) {
  var val;
  if (value === null || value === undefined) {
    return value;
  }
  val = Buffer.isBuffer(value) ? value.toString('utf8') : value;
  if (cast !== false && typeof val === 'string') {
    try {
      return JSON.parse(val);
    } catch (e) {}
  }
  return val;
}
915927
public <T> T convert(Object value, Class<T> type) {
		return converter.convert(value, type);
	}
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;
    }
217597
def _cast_to_type(self, value):
        
        if isinstance(value, str) or value is None:
            return value
        return str(value)
74968
private void determineValueType(Object value){
		if (value instanceof Integer){
			this.valueEncoder.valueType = INTEGER;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(4).putInt((Integer)value).array();
		}
		else if (value instanceof Long) {
			this.valueEncoder.valueType = LONG;
			this.valueEncoder.valueBytes = ByteBuffer.allocate(8).putLong((Long)value).array();
		}
		else if (value == null){
			this.valueEncoder.valueType = NULL;
		}
		else {
			ObjectOutputStream oos = null;
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				oos = new ObjectOutputStream(bos);
				oos.writeObject(value);
				this.valueEncoder.valueType = OBJECT;
				this.valueEncoder.valueBytes = bos.toByteArray();
			} catch (Exception e) {
				throw new IllegalStateException("Failed to serialize value: " + value, e);
			} finally {
				try {
					if (oos != null){
						oos.close();
					}
				} catch (Exception e2) {/*ignore*/}
			}
		}
	}
528567
def cast_value(self, value, constraints=True):
        

        # Null value
        if value in self.__missing_values:
            value = None

        # Cast value
        cast_value = value
        if value is not None:
            cast_value = self.__cast_function(value)
            if cast_value == config.ERROR:
                raise exceptions.CastError((
                    'Field "{field.name}" can\'t cast value "{value}" '
                    'for type "{field.type}" with format "{field.format}"'
                    ).format(field=self, value=value))

        # Check value
        if constraints:
            for name, check in self.__check_functions.items():
                if isinstance(constraints, list):
                    if name not in constraints:
                        continue
                passed = check(cast_value)
                if not passed:
                    raise exceptions.CastError((
                        'Field "{field.name}" has constraint "{name}" '
                        'which is not satisfied for value "{value}"'
                        ).format(field=self, name=name, value=value))

        return cast_value