Java Object Type Case cast(Class toType, Object value)

Here you can find the source of cast(Class toType, Object value)

Description

Converts the given value to the required type or throw a meaningful exception

License

Apache License

Declaration

@SuppressWarnings("unchecked")
public static <T> T cast(Class<T> toType, Object value) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from ww  w  .  ja  v  a  2s .com*/
     * Converts the given value to the required type or throw a meaningful exception
     */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Class<T> toType, Object value) {
        if (toType == boolean.class) {
            return (T) cast(Boolean.class, value);
        } else if (toType.isPrimitive()) {
            Class newType = convertPrimitiveTypeToWrapperType(toType);
            if (newType != toType) {
                return (T) cast(newType, value);
            }
        }
        try {
            return toType.cast(value);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "Failed to convert: " + value + " to type: " + toType.getName() + " due to: " + e, e);
        }
    }

    /**
     * Converts primitive types such as int to its wrapper type like
     * {@link Integer}
     */
    public static Class<?> convertPrimitiveTypeToWrapperType(Class<?> type) {
        Class<?> rc = type;
        if (type.isPrimitive()) {
            if (type == int.class) {
                rc = Integer.class;
            } else if (type == long.class) {
                rc = Long.class;
            } else if (type == double.class) {
                rc = Double.class;
            } else if (type == float.class) {
                rc = Float.class;
            } else if (type == short.class) {
                rc = Short.class;
            } else if (type == byte.class) {
                rc = Byte.class;
            } else if (type == boolean.class) {
                rc = Boolean.class;
            }
        }
        return rc;
    }
}

Related

  1. cast(Class c, Object o)
  2. cast(Class clazz, Object o, T def)
  3. cast(Class clazz, Object obj)
  4. cast(Class clazz, Object object)
  5. cast(Class targetClass, Object obj)
  6. cast(Class type, Object key, Object value)
  7. cast(Class type, Object obj)
  8. cast(double[] arr)
  9. cast(final Class clazz)