Here you can find the source of cast(Object val, Class type)
public static Object cast(Object val, Class type) throws ClassCastException
//package com.java2s; //License from project: Apache License public class Main { public static Object cast(Object val, Class type) throws ClassCastException { if (val == null) return null; if (type == Boolean.class || type == Boolean.TYPE) { return ((Boolean) val).booleanValue(); } else if (type == Character.class || type == Character.TYPE) { return ((Character) val).charValue(); } else if (type == Byte.class || type == Byte.TYPE) { return ((Byte) val).byteValue(); } else if (type == Short.class || type == Short.TYPE) { if (val instanceof Long) return ((Long) val).shortValue(); else if (val instanceof Integer) return ((Integer) val).shortValue(); else if (val instanceof Short) return ((Short) val).shortValue(); } else if (type == Integer.class || type == Integer.TYPE) { if (val instanceof Long) return ((Long) val).intValue(); else if (val instanceof Integer) return ((Integer) val).intValue(); } else if (type == Long.class || type == Long.TYPE) { if (val instanceof Integer) return ((Integer) val).longValue(); else if (val instanceof Long) return ((Long) val).longValue(); } else if (type == Float.class || type == Float.TYPE) { if (val instanceof Double) return ((Double) val).floatValue(); else if (val instanceof Float) return ((Float) val).floatValue(); } else if (type == Double.class || type == Double.TYPE) { if (val instanceof Double) return ((Double) val).doubleValue(); else if (val instanceof Float) return ((Float) val).doubleValue(); } else if (type.isAssignableFrom(val.getClass())) { return type.cast(val); }/*from ww w . jav a 2s. c o m*/ return null; } }