Example usage for java.lang Number byteValue

List of usage examples for java.lang Number byteValue

Introduction

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

Prototype

public byte byteValue() 

Source Link

Document

Returns the value of the specified number as a byte .

Usage

From source file:Main.java

public static void main(String[] args) {
    // get a number as integer
    Number x = new Integer(123456);

    // get a number as float
    Number y = new Float(9876f);

    // print their value as byte
    System.out.println("x as integer:" + x + ", x as byte:" + x.byteValue());
    System.out.println("y as float:" + y + ", y as byte:" + y.byteValue());

}

From source file:Main.java

public static byte[] toByteArray(Collection<? extends Number> c) {
    byte arr[] = new byte[c.size()];
    int i = 0;/*w  w  w.  j  av a2  s .co m*/
    for (Number item : c) {
        arr[i++] = item.byteValue();
    }
    return arr;
}

From source file:Main.java

public static byte[] toByteArray(Collection<? extends Number> c) {
    byte arr[] = new byte[c.size()];
    int i = 0;/*from  w w  w .  j a  v  a 2  s .  c  o  m*/
    for (Number item : c)
        arr[i++] = item.byteValue();
    return arr;
}

From source file:io.fabric8.jolokia.support.JolokiaHelpers.java

public static Object convertJolokiaToJavaType(Class<?> clazz, Object value) throws IOException {
    if (clazz.isArray()) {
        if (value instanceof JSONArray) {
            JSONArray jsonArray = (JSONArray) value;
            Object[] javaArray = (Object[]) Array.newInstance(clazz.getComponentType(), jsonArray.size());
            int idx = 0;
            for (Object element : jsonArray) {
                Array.set(javaArray, idx++, convertJolokiaToJavaType(clazz.getComponentType(), element));
            }/*from www. ja  va 2  s .com*/
            return javaArray;
        } else {
            return null;
        }
    } else if (String.class.equals(clazz)) {
        return (value != null) ? value.toString() : null;
    } else if (clazz.equals(Byte.class) || clazz.equals(byte.class)) {
        Number number = asNumber(value);
        return number != null ? number.byteValue() : null;
    } else if (clazz.equals(Short.class) || clazz.equals(short.class)) {
        Number number = asNumber(value);
        return number != null ? number.shortValue() : null;
    } else if (clazz.equals(Integer.class) || clazz.equals(int.class)) {
        Number number = asNumber(value);
        return number != null ? number.intValue() : null;
    } else if (clazz.equals(Long.class) || clazz.equals(long.class)) {
        Number number = asNumber(value);
        return number != null ? number.longValue() : null;
    } else if (clazz.equals(Float.class) || clazz.equals(float.class)) {
        Number number = asNumber(value);
        return number != null ? number.floatValue() : null;
    } else if (clazz.equals(Double.class) || clazz.equals(double.class)) {
        Number number = asNumber(value);
        return number != null ? number.doubleValue() : null;
    } else if (value instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) value;
        if (!JSONObject.class.isAssignableFrom(clazz)) {
            String json = jsonObject.toJSONString();
            return getObjectMapper().readerFor(clazz).readValue(json);
        }
    }
    return value;
}

From source file:mil.jpeojtrs.sca.util.PrimitiveArrayUtils.java

public static byte[] convertToByteArray(final Object array) {
    if (array == null) {
        return null;
    }//from w  ww  . j  a v  a 2 s  .  c om
    if (array instanceof byte[]) {
        return (byte[]) array;
    }
    if (array instanceof Byte[]) {
        return ArrayUtils.toPrimitive((Byte[]) array);
    }
    final byte[] newArray = new byte[Array.getLength(array)];
    for (int i = 0; i < newArray.length; i++) {
        final Number val = (Number) Array.get(array, i);
        newArray[i] = val.byteValue();
    }
    return newArray;
}

From source file:net.dontdrinkandroot.utils.lang.math.NumberUtils.java

/**
 * Get the null safe byteValue of a Number. Defaults to 0.
 * /*www. j a v a 2s.  c om*/
 * @param number
 *            The Number to convert.
 * @return The null safe byteValue. Defaults to 0.
 */
public static byte byteValue(final Number number) {

    if (number == null) {
        return 0;
    }

    return number.byteValue();
}

From source file:gedi.util.MathUtils.java

/**
 * Throws an exception if n is either a real or to big to be represented by a byte.
 * @param n/*from   w w w  .  j  av  a 2s. c o  m*/
 * @return
 */
public static byte byteValueExact(Number n) {
    if (n instanceof Byte)
        return n.byteValue();
    double d = n.doubleValue();
    long l = n.longValue();
    if (d == (double) l) {
        if (l >= Byte.MIN_VALUE && l <= Byte.MAX_VALUE)
            return (byte) l;
    }
    throw new NumberFormatException();
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

@SuppressWarnings("squid:S3776")
private static Object convertPrimitiveValue(String value, Class<?> type) throws ParseException {
    if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) {
        return value.toLowerCase().trim().equals("true");
    } else {// w  ww .ja va  2  s.co  m
        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        Number num = numberFormat.parse(value);
        if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            return num.byteValue();
        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            return num.doubleValue();
        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            return num.floatValue();
        } else if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            return num.intValue();
        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            return num.longValue();
        } else if (type.equals(Short.class) || type.equals(Short.TYPE)) {
            return num.shortValue();
        } else {
            return null;
        }
    }
}

From source file:Main.java

/**
 * convert value to given type.//  w w  w.j  av  a  2 s . co 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;/*  w ww.j  a v a2s  .  co  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());
}