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:Main.java

/**
 * convert value to given type./*w w  w .j  a  v  a 2 s  . c o  m*/
 * null safe.
 *
 * @param value value for convert
 * @param type  will converted type
 * @return value while converted
 */
public static Object convertCompatibleType(Object value, Class<?> type) {

    if (value == null || type == null || type.isAssignableFrom(value.getClass())) {
        return value;
    }
    if (value instanceof String) {
        String string = (String) value;
        if (char.class.equals(type) || Character.class.equals(type)) {
            if (string.length() != 1) {
                throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!"
                        + " when convert String to char, the String MUST only 1 char.", string));
            }
            return string.charAt(0);
        } else if (type.isEnum()) {
            return Enum.valueOf((Class<Enum>) type, string);
        } else if (type == BigInteger.class) {
            return new BigInteger(string);
        } else if (type == BigDecimal.class) {
            return new BigDecimal(string);
        } else if (type == Short.class || type == short.class) {
            return Short.valueOf(string);
        } else if (type == Integer.class || type == int.class) {
            return Integer.valueOf(string);
        } else if (type == Long.class || type == long.class) {
            return Long.valueOf(string);
        } else if (type == Double.class || type == double.class) {
            return Double.valueOf(string);
        } else if (type == Float.class || type == float.class) {
            return Float.valueOf(string);
        } else if (type == Byte.class || type == byte.class) {
            return Byte.valueOf(string);
        } else if (type == Boolean.class || type == boolean.class) {
            return Boolean.valueOf(string);
        } else if (type == Date.class) {
            try {
                return new SimpleDateFormat(DATE_FORMAT).parse((String) value);
            } catch (ParseException e) {
                throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT
                        + ", cause: " + e.getMessage(), e);
            }
        } else if (type == Class.class) {
            return forName((String) value);
        }
    } else if (value instanceof Number) {
        Number number = (Number) value;
        if (type == byte.class || type == Byte.class) {
            return number.byteValue();
        } else if (type == short.class || type == Short.class) {
            return number.shortValue();
        } else if (type == int.class || type == Integer.class) {
            return number.intValue();
        } else if (type == long.class || type == Long.class) {
            return number.longValue();
        } else if (type == float.class || type == Float.class) {
            return number.floatValue();
        } else if (type == double.class || type == Double.class) {
            return number.doubleValue();
        } else if (type == BigInteger.class) {
            return BigInteger.valueOf(number.longValue());
        } else if (type == BigDecimal.class) {
            return BigDecimal.valueOf(number.doubleValue());
        } else if (type == Date.class) {
            return new Date(number.longValue());
        }
    } else if (value instanceof Collection) {
        Collection collection = (Collection) value;
        if (type.isArray()) {
            int length = collection.size();
            Object array = Array.newInstance(type.getComponentType(), length);
            int i = 0;
            for (Object item : collection) {
                Array.set(array, i++, item);
            }
            return array;
        } else if (!type.isInterface()) {
            try {
                Collection result = (Collection) type.newInstance();
                result.addAll(collection);
                return result;
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (type == List.class) {
            return new ArrayList<>(collection);
        } else if (type == Set.class) {
            return new HashSet<>(collection);
        }
    } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) {
        Collection collection;
        if (!type.isInterface()) {
            try {
                collection = (Collection) type.newInstance();
            } catch (Throwable e) {
                collection = new ArrayList<>();
            }
        } else if (type == Set.class) {
            collection = new HashSet<>();
        } else {
            collection = new ArrayList<>();
        }
        int length = Array.getLength(value);
        for (int i = 0; i < length; i++) {
            collection.add(Array.get(value, i));
        }
        return collection;
    }
    return value;
}

From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class toType, Object value) {
    if ("".equals(value)) {
        value = null;//from w ww.jav  a 2  s  .c  o  m
    }
    // If we do not want a collection, but the value is one, use the first value
    if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray())
            && (value.getClass().isArray() || value instanceof Collection)) {
        final Iterator it = IteratorUtils.getIterator(value);
        if (!it.hasNext()) {
            value = null;
        } else {
            value = it.next();
        }
    }

    // Check for null values
    if (value == null) {
        if (toType.isPrimitive()) {
            // On primitives, use the default value
            if (toType == Boolean.TYPE) {
                value = Boolean.FALSE;
            } else if (toType == Character.TYPE) {
                value = '\0';
            } else {
                value = 0;
            }
        } else {
            // For objects, return null
            return null;
        }
    }

    // Check if the value is already of the expected type
    if (toType.isInstance(value)) {
        return value;
    }

    // If the class is primitive, use the wrapper, so we have an easier work of testing instances
    if (toType.isPrimitive()) {
        toType = ClassUtils.primitiveToWrapper(toType);
    }

    // Convert to well-known types
    if (String.class.isAssignableFrom(toType)) {
        if (value instanceof Entity) {
            final Long entityId = ((Entity) value).getId();
            return entityId == null ? null : entityId.toString();
        }
        return value.toString();
    } else if (Number.class.isAssignableFrom(toType)) {
        if (!(value instanceof Number)) {
            if (value instanceof String) {
                value = new BigDecimal((String) value);
            } else if (value instanceof Date) {
                value = ((Date) value).getTime();
            } else if (value instanceof Calendar) {
                value = ((Calendar) value).getTimeInMillis();
            } else if (value instanceof Entity) {
                value = ((Entity) value).getId();
                if (value == null) {
                    return null;
                }
            } else {
                throw new ConversionException("Invalid number: " + value);
            }
        }
        final Number number = (Number) value;
        if (Byte.class.isAssignableFrom(toType)) {
            return number.byteValue();
        } else if (Short.class.isAssignableFrom(toType)) {
            return number.shortValue();
        } else if (Integer.class.isAssignableFrom(toType)) {
            return number.intValue();
        } else if (Long.class.isAssignableFrom(toType)) {
            return number.longValue();
        } else if (Float.class.isAssignableFrom(toType)) {
            return number.floatValue();
        } else if (Double.class.isAssignableFrom(toType)) {
            return number.doubleValue();
        } else if (BigInteger.class.isAssignableFrom(toType)) {
            return new BigInteger(number.toString());
        } else if (BigDecimal.class.isAssignableFrom(toType)) {
            return new BigDecimal(number.toString());
        }
    } else if (Boolean.class.isAssignableFrom(toType)) {
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if ("on".equalsIgnoreCase(value.toString())) {
            return true;
        } else {
            return Boolean.parseBoolean(value.toString());
        }
    } else if (Character.class.isAssignableFrom(toType)) {
        final String str = value.toString();
        return (str.length() == 0) ? null : str.charAt(0);
    } else if (Calendar.class.isAssignableFrom(toType)) {
        if (value instanceof Date) {
            final Calendar cal = new GregorianCalendar();
            cal.setTime((Date) value);
            return cal;
        }
    } else if (Date.class.isAssignableFrom(toType)) {
        if (value instanceof Calendar) {
            final long millis = ((Calendar) value).getTimeInMillis();
            try {
                return ConstructorUtils.invokeConstructor(toType, millis);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    } else if (Enum.class.isAssignableFrom(toType)) {
        Object ret;
        try {
            ret = Enum.valueOf(toType, value.toString());
        } catch (final Exception e) {
            ret = null;
        }
        if (ret == null) {
            Object[] possible;
            try {
                possible = (Object[]) toType.getMethod("values").invoke(null);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Couldn't invoke the 'values' method for enum " + toType.getName());
            }
            if (StringValuedEnum.class.isAssignableFrom(toType)) {
                final String test = coerce(String.class, value);
                for (final Object item : possible) {
                    if (((StringValuedEnum) item).getValue().equals(test)) {
                        ret = item;
                        break;
                    }
                }
            } else if (IntValuedEnum.class.isAssignableFrom(toType)) {
                final int test = coerce(Integer.TYPE, value);
                for (final Object item : possible) {
                    if (((IntValuedEnum) item).getValue() == test) {
                        ret = item;
                        break;
                    }
                }
            } else {
                throw new ConversionException("Invalid enum: " + value);
            }
        }
        return ret;
    } else if (Entity.class.isAssignableFrom(toType)) {
        final Long id = coerce(Long.class, value);
        return EntityHelper.reference(toType, id);
    } else if (Locale.class.isAssignableFrom(toType)) {
        return LocaleConverter.instance().valueOf(value.toString());
    } else if (Collection.class.isAssignableFrom(toType)) {
        final Collection collection = (Collection) ClassHelper.instantiate(toType);
        final Iterator iterator = IteratorUtils.getIterator(value);
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
        return collection;
    } else if (toType.isArray()) {
        final Collection collection = coerceCollection(toType.getComponentType(), value);
        final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size());
        return collection.toArray(array);
    }

    // We don't know how to convert the value
    throw new ConversionException("Cannot coerce value to: " + toType.getName());
}

From source file:org.batoo.jpa.common.reflect.ReflectHelper.java

/**
 * Converts the number into number Type/*from   ww  w  . j  a  v  a 2 s.co  m*/
 * 
 * @param value
 *            the number value
 * @param numberType
 *            the number type
 * @return the converted number value
 * 
 * @since $version
 * @author hceylan
 */
public static Number convertNumber(Number value, Class<?> numberType) {
    if (numberType == Integer.class) {
        return value.intValue();
    }

    if (numberType == Long.class) {
        return value.longValue();
    }

    if (numberType == Short.class) {
        return value.shortValue();
    }

    if (numberType == Byte.class) {
        return value.byteValue();
    }

    if (numberType == Float.class) {
        return value.floatValue();
    }

    if (numberType == Double.class) {
        return value.doubleValue();
    }

    throw new IllegalArgumentException(numberType + " not supported");
}

From source file:org.briljantframework.data.vector.Convert.java

@SuppressWarnings("unchecked")
private static <T> T convertNumber(Class<T> cls, Number num) {
    if (cls.equals(Double.class) || cls.equals(Double.TYPE)) {
        return (T) (Double) num.doubleValue();
    } else if (cls.equals(Float.class) || cls.equals(Float.TYPE)) {
        return (T) (Float) num.floatValue();
    } else if (cls.equals(Long.class) || cls.equals(Long.TYPE)) {
        return (T) (Long) num.longValue();
    } else if (cls.equals(Integer.class) || cls.equals(Integer.TYPE)) {
        return (T) (Integer) num.intValue();
    } else if (cls.equals(Short.class) || cls.equals(Short.TYPE)) {
        return (T) (Short) num.shortValue();
    } else if (cls.equals(Byte.class) || cls.equals(Byte.TYPE)) {
        return (T) (Byte) num.byteValue();
    } else if (Complex.class.equals(cls)) {
        return cls.cast(Complex.valueOf(num.doubleValue()));
    } else if (Logical.class.equals(cls)) {
        return cls.cast(num.intValue() == 1 ? Logical.TRUE : Logical.FALSE);
    } else if (Boolean.class.equals(cls)) {
        return cls.cast(num.intValue() == 1);
    } else {//from  w w  w. j ava  2 s . c  o m
        return Na.of(cls);
    }
}

From source file:com.amazonaws.hal.client.ConversionUtil.java

private static Object convertFromNumber(Class<?> clazz, Number value) {
    if (String.class.isAssignableFrom(clazz)) {
        return value.toString();
    } else if (int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)) {
        return value.intValue();
    } else if (long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)) {
        return value.longValue();
    } else if (short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)) {
        return value.shortValue();
    } else if (double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)) {
        return value.doubleValue();
    } else if (float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)) {
        return value.floatValue();
    } else if (boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) {
        return Boolean.valueOf(value.toString());
    } else if (char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) {
        if (value.longValue() <= 255) {
            return (char) value.longValue();
        } else {//from w  w w.j a  v  a 2 s.c  o  m
            throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
        }
    } else if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)) {
        return value.byteValue();
    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
        return new BigDecimal(value.toString());
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        // Necessary because BigInteger(long) is a private method and we need to convert the Number to a long to
        // prevent the constructor from throwing a NumberFormatException Example: BigInteger(1.2)
        return new BigInteger(String.valueOf(value.longValue()));
    } else if (Date.class.isAssignableFrom(clazz)) {
        return new Date(value.longValue());
    } else if (clazz.isEnum()) {
        try {
            //noinspection unchecked
            return Enum.valueOf((Class<Enum>) clazz, value.toString());
        } catch (IllegalArgumentException e) {
            log.error(String.format(
                    "'%s' is not a recognized enum value for %s.  Returning default of %s instead.", value,
                    clazz.getName(), clazz.getEnumConstants()[0]));

            return clazz.getEnumConstants()[0];
        }
    } else {
        throw new RuntimeException("Not sure how to convert " + value + " to a " + clazz.getSimpleName());
    }
}

From source file:voldemort.VoldemortClientShell.java

@SuppressWarnings("unchecked")
protected static Object tightenNumericTypes(Object o) {
    if (o == null) {
        return null;
    } else if (o instanceof List) {
        List l = (List) o;
        for (int i = 0; i < l.size(); i++)
            l.set(i, tightenNumericTypes(l.get(i)));
        return l;
    } else if (o instanceof Map) {
        Map m = (Map) o;// w  w w.  j  av  a  2 s .c om
        for (Map.Entry entry : (Set<Map.Entry>) m.entrySet())
            m.put(entry.getKey(), tightenNumericTypes(entry.getValue()));
        return m;
    } else if (o instanceof Number) {
        Number n = (Number) o;
        if (o instanceof Integer) {
            if (n.intValue() < Byte.MAX_VALUE)
                return n.byteValue();
            else if (n.intValue() < Short.MAX_VALUE)
                return n.shortValue();
            else
                return n;
        } else if (o instanceof Double) {
            if (n.doubleValue() < Float.MAX_VALUE)
                return n.floatValue();
            else
                return n;
        } else {
            throw new RuntimeException("Unsupported numeric type: " + o.getClass());
        }
    } else {
        return o;
    }
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a short primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)vv//from  ww w.  j av  a2 s.  c  om
 *@return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}

From source file:org.lingcloud.molva.ocl.util.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a short primitive.
 * /* w ww  .  j a  va2s.  co  m*/
 * @param value
 *            The value validation is being performed on.
 * @param locale
 *            The locale to use to parse the number (system default if
 *            null)vv
 * @return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = Short.valueOf(num.shortValue());
            }
        }
    }

    return result;
}

From source file:net.yck.wkrdb.common.shared.PropertyConverter.java

/**
 * Convert the specified object into a Short.
 *
 * @param value//  w w  w. j a v  a2  s . c om
 *            the value to convert
 * @return the converted value
 * @throws ConversionException
 *             thrown if the value cannot be converted to a short
 */
public static Short toShort(Object value) throws ConversionException {
    Number n = toNumber(value, Short.class);
    if (n instanceof Short) {
        return (Short) n;
    } else {
        return n.shortValue();
    }
}

From source file:easyJ.common.validate.GenericTypeValidator.java

/**
 * Checks if the value can safely be converted to a short primitive.
 * //from   w  ww  .  j  a va 2  s . com
 * @param value
 *                The value validation is being performed on.
 * @param locale
 *                The locale to use to parse the number (system default if
 *                null)vv
 * @return the converted Short value.
 */
public static Short formatShort(String value, Locale locale) {
    Short result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) {
                result = new Short(num.shortValue());
            }
        }
    }

    return result;
}