Here you can find the source of cast(Class
@SuppressWarnings("unchecked") public static <T> T cast(Class<T> toType, Object value)
//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; } }