Example usage for java.lang Number shortValue

List of usage examples for java.lang Number shortValue

Introduction

In this page you can find the example usage for java.lang Number shortValue.

Prototype

public short shortValue() 

Source Link

Document

Returns the value of the specified number as a short .

Usage

From source file:org.op4j.functions.FnShort.java

private static Short fromNumber(final Number number) {
    if (number == null) {
        return null;
    }/*from   w  ww .  j  ava 2s.  c o m*/
    return Short.valueOf(number.shortValue());
}

From source file:weave.servlets.WeaveServlet.java

/**
 * Tries to convert value to the given type.
 * @param value The value to cast to a new type.
 * @param type The desired type.//from   w  w  w . j  a v  a 2s.c  o  m
 * @return The value, which may have been cast as the new type.
 */
protected Object cast(Object value, Class<?> type) throws RemoteException {
    if (type.isInstance(value))
        return value;

    try {
        if (value == null) // null -> NaN
        {
            if (type == double.class || type == Double.class)
                value = Double.NaN;
            else if (type == float.class || type == Float.class)
                value = Float.NaN;
            return value;
        }

        if (value instanceof Map) // Map -> Java Bean
        {
            Object bean = type.newInstance();
            for (Field field : type.getFields()) {
                Object fieldValue = ((Map<?, ?>) value).get(field.getName());
                fieldValue = cast(fieldValue, field.getType());
                field.set(bean, fieldValue);
            }
            return bean;
        }

        if (type.isArray()) // ? -> T[]
        {
            if (value instanceof String) // String -> String[]
                value = CSVParser.defaultParser.parseCSVRow((String) value, true);

            if (value instanceof List) // List -> Object[]
                value = ((List<?>) value).toArray();

            if (value.getClass().isArray()) // T1[] -> T2[]
            {
                int n = Array.getLength(value);
                Class<?> itemType = type.getComponentType();
                Object output = Array.newInstance(itemType, n);
                while (n-- > 0)
                    Array.set(output, n, cast(Array.get(value, n), itemType));
                return output;
            }
        }

        if (Collection.class.isAssignableFrom(type)) // ? -> <? extends Collection>
        {
            value = cast(value, Object[].class); // ? -> Object[]

            if (value.getClass().isArray()) // T1[] -> Vector<T2>
            {
                int n = Array.getLength(value);
                List<Object> output = new Vector<Object>(n);
                TypeVariable<?>[] itemTypes = type.getTypeParameters();
                Class<?> itemType = itemTypes.length > 0 ? itemTypes[0].getClass() : null;
                while (n-- > 0) {
                    Object item = Array.get(value, n);
                    if (itemType != null)
                        item = cast(item, itemType); // T1 -> T2
                    output.set(n, item);
                }
                return output;
            }
        }

        if (value instanceof String) // String -> ?
        {
            String string = (String) value;

            // String -> primitive
            if (type == char.class || type == Character.class)
                return string.charAt(0);
            if (type == byte.class || type == Byte.class)
                return Byte.parseByte(string);
            if (type == long.class || type == Long.class)
                return Long.parseLong(string);
            if (type == int.class || type == Integer.class)
                return Integer.parseInt(string);
            if (type == short.class || type == Short.class)
                return Short.parseShort(string);
            if (type == float.class || type == Float.class)
                return Float.parseFloat(string);
            if (type == double.class || type == Double.class)
                return Double.parseDouble(string);
            if (type == boolean.class || type == Boolean.class)
                return string.equalsIgnoreCase("true");

            if (type == InputStream.class) // String -> InputStream
            {
                try {
                    return new ByteArrayInputStream(string.getBytes("UTF-8"));
                } catch (Exception e) {
                    return null;
                }
            }
        }

        if (value instanceof Number) // Number -> primitive
        {
            Number number = (Number) value;
            if (type == byte.class || type == Byte.class)
                return number.byteValue();
            if (type == long.class || type == Long.class)
                return number.longValue();
            if (type == int.class || type == Integer.class)
                return number.intValue();
            if (type == short.class || type == Short.class)
                return number.shortValue();
            if (type == float.class || type == Float.class)
                return number.floatValue();
            if (type == double.class || type == Double.class)
                return number.doubleValue();
            if (type == char.class || type == Character.class)
                return Character.toChars(number.intValue())[0];
            if (type == boolean.class || type == Boolean.class)
                return !Double.isNaN(number.doubleValue()) && number.intValue() != 0;
        }
    } catch (Exception e) {
        throw new RemoteException(String.format("Unable to cast %s to %s", value.getClass().getSimpleName(),
                type.getSimpleName()), e);
    }

    // Return original value if not handled above.
    // Primitives and their Object equivalents will cast automatically.
    return value;
}

From source file:com.xtructure.xevolution.genetics.impl.AbstractPopulation.java

/**
 * Adds the attribute in the given {@link Genome} with the given
 * {@link XValId} to the corresponding value in the accumulation map.
 * /*w  w  w  .  ja v  a  2s.com*/
 * @param <V>
 *            the type of the attribute
 * @param valueId
 *            the id of the attribute
 * @param accMap
 *            the accumulation map
 * @param genome
 *            the {@link Genome} from which to get the attribute
 */
private <V extends Comparable<V>> void updateAccMap(XValId<V> valueId, ValueMap accMap, Genome<D> genome) {
    getLogger().trace("begin %s.updateAccMap(%s, %s, %s)", getClass().getSimpleName(), valueId, accMap, genome);
    if (Number.class.isAssignableFrom(valueId.getType())) {
        if (accMap.get(valueId) == null) {
            accMap.set(//
                    valueId, //
                    genome.getAttribute(valueId));
        } else {
            Number acc = (Number) accMap.get(valueId);
            Number nxt = (Number) genome.getAttribute(valueId);
            Number sum = null;
            ValueType type = ValueType.getValueType(valueId.getType());
            if (type != null) {
                switch (type) {
                case DOUBLE:
                    sum = acc.doubleValue() + nxt.doubleValue();
                    break;
                case FLOAT:
                    sum = acc.floatValue() + nxt.floatValue();
                    break;
                case LONG:
                    sum = acc.longValue() + nxt.longValue();
                    break;
                case INTEGER:
                    sum = acc.intValue() + nxt.intValue();
                    break;
                case SHORT:
                    sum = acc.shortValue() + nxt.shortValue();
                    break;
                case BYTE:
                    sum = acc.byteValue() + nxt.byteValue();
                    break;
                default:
                    break;
                }
                @SuppressWarnings("unchecked")
                V v = (V) sum;
                accMap.set(valueId, v);
            }
        }
    }
    getLogger().trace("end %s.updateAccMap()", getClass().getSimpleName());
}

From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java

/**
 * Convert any Number object to the specified type for this
 * <i>Converter</i>./*from ww w.  j a v a  2s  .c  o m*/
 * <p>
 * This method handles conversion to the following types:
 * <ul>
 *     <li><code>java.lang.Byte</code></li>
 *     <li><code>java.lang.Short</code></li>
 *     <li><code>java.lang.Integer</code></li>
 *     <li><code>java.lang.Long</code></li>
 *     <li><code>java.lang.Float</code></li>
 *     <li><code>java.lang.Double</code></li>
 *     <li><code>java.math.BigDecimal</code></li>
 *     <li><code>java.math.BigInteger</code></li>
 * </ul>
 * @param sourceType The type being converted from
 * @param targetType The Number type to convert to
 * @param value The Number to convert.
 *
 * @return The converted value.
 */
private Number toNumber(Class sourceType, Class targetType, Number value) {

    // Correct Number type already
    if (targetType.equals(value.getClass())) {
        return value;
    }

    // Byte
    if (targetType.equals(Byte.class)) {
        long longValue = value.longValue();
        if (longValue > Byte.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Byte.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Byte(value.byteValue());
    }

    // Short
    if (targetType.equals(Short.class)) {
        long longValue = value.longValue();
        if (longValue > Short.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Short.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Short(value.shortValue());
    }

    // Integer
    if (targetType.equals(Integer.class)) {
        long longValue = value.longValue();
        if (longValue > Integer.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Integer.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Integer(value.intValue());
    }

    // Long
    if (targetType.equals(Long.class)) {
        return new Long(value.longValue());
    }

    // Float
    if (targetType.equals(Float.class)) {
        if (value.doubleValue() > Float.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        return new Float(value.floatValue());
    }

    // Double
    if (targetType.equals(Double.class)) {
        return new Double(value.doubleValue());
    }

    // BigDecimal
    if (targetType.equals(BigDecimal.class)) {
        if (value instanceof Float || value instanceof Double) {
            return new BigDecimal(value.toString());
        } else if (value instanceof BigInteger) {
            return new BigDecimal((BigInteger) value);
        } else {
            return BigDecimal.valueOf(value.longValue());
        }
    }

    // BigInteger
    if (targetType.equals(BigInteger.class)) {
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).toBigInteger();
        } else {
            return BigInteger.valueOf(value.longValue());
        }
    }

    String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'";
    throw new ConversionException(msg);

}

From source file:javadz.beanutils.converters.NumberConverter.java

/**
 * Convert any Number object to the specified type for this
 * <i>Converter</i>./*from   w  ww . j  a  v a  2s . c om*/
 * <p>
 * This method handles conversion to the following types:
 * <ul>
 *     <li><code>java.lang.Byte</code></li>
 *     <li><code>java.lang.Short</code></li>
 *     <li><code>java.lang.Integer</code></li>
 *     <li><code>java.lang.Long</code></li>
 *     <li><code>java.lang.Float</code></li>
 *     <li><code>java.lang.Double</code></li>
 *     <li><code>java.math.BigDecimal</code></li>
 *     <li><code>java.math.BigInteger</code></li>
 * </ul>
 * @param sourceType The type being converted from
 * @param targetType The Number type to convert to
 * @param value The Number to convert.
 *
 * @return The converted value.
 */
private Number toNumber(Class sourceType, Class targetType, Number value) {

    // Correct Number type already
    if (targetType.equals(value.getClass())) {
        return value;
    }

    // Byte
    if (targetType.equals(Byte.class)) {
        long longValue = value.longValue();
        if (longValue > Byte.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Byte.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Byte(value.byteValue());
    }

    // Short
    if (targetType.equals(Short.class)) {
        long longValue = value.longValue();
        if (longValue > Short.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Short.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Short(value.shortValue());
    }

    // Integer
    if (targetType.equals(Integer.class)) {
        long longValue = value.longValue();
        if (longValue > Integer.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        if (longValue < Integer.MIN_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too small " + toString(targetType));
        }
        return new Integer(value.intValue());
    }

    // Long
    if (targetType.equals(Long.class)) {
        return new Long(value.longValue());
    }

    // Float
    if (targetType.equals(Float.class)) {
        if (value.doubleValue() > Float.MAX_VALUE) {
            throw new ConversionException(
                    toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType));
        }
        return new Float(value.floatValue());
    }

    // Double
    if (targetType.equals(Double.class)) {
        return new Double(value.doubleValue());
    }

    // BigDecimal
    if (targetType.equals(BigDecimal.class)) {
        if (value instanceof Float || value instanceof Double) {
            return new BigDecimal(value.toString());
        } else if (value instanceof BigInteger) {
            return new BigDecimal((BigInteger) value);
        } else {
            return BigDecimal.valueOf(value.longValue());
        }
    }

    // BigInteger
    if (targetType.equals(BigInteger.class)) {
        if (value instanceof BigDecimal) {
            return ((BigDecimal) value).toBigInteger();
        } else {
            return BigInteger.valueOf(value.longValue());
        }
    }

    String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'";
    if (log().isWarnEnabled()) {
        log().warn("    " + msg);
    }
    throw new ConversionException(msg);

}

From source file:org.structr.core.entity.AbstractNode.java

private Object convert(Object value, Class type) {

    Object convertedObject = null;

    if (type.equals(String.class)) {

        // strings can be returned immediately
        return value.toString();

    } else if (value instanceof Number) {

        Number number = (Number) value;

        if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            return number.intValue();

        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            return number.longValue();

        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            return number.doubleValue();

        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            return number.floatValue();

        } else if (type.equals(Short.class) || type.equals(Integer.TYPE)) {
            return number.shortValue();

        } else if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            return number.byteValue();

        }//from   w  w w .j a  va 2 s.co  m

    } else if (value instanceof List) {

        return value;

    } else if (value instanceof Map) {
        return value;
    }

    // fallback
    try {

        Method valueOf = type.getMethod("valueOf", String.class);
        if (valueOf != null) {

            convertedObject = valueOf.invoke(null, value.toString());

        } else {

            logger.log(Level.WARNING, "Unable to find static valueOf method for type {0}", type);
        }

    } catch (Throwable t) {

        logger.log(Level.WARNING,
                "Unable to deserialize value {0} of type {1}, Class has no static valueOf method.",
                new Object[] { value, type });
    }

    return convertedObject;
}