Here you can find the source of castToPrimitive(Object start, Class
@SuppressWarnings("unchecked") public static <T> T castToPrimitive(Object start, Class<T> prim)
//package com.java2s; //License from project: Apache License import java.util.HashMap; import java.util.Map; public class Main { private static final Map<Class<?>, Object> defaultPrimitiveValues = new HashMap<>(); @SuppressWarnings("unchecked") public static <T> T castToPrimitive(Object start, Class<T> prim) { try {/*from w w w . j av a 2 s.c o m*/ if (start == null) { return (T) defaultPrimitiveValues.get(prim); } if (start instanceof Boolean) { start = ((Boolean) start) ? 1 : 0; } if (start instanceof Character) { start = (int) ((Character) start).charValue(); } if (prim == char.class) { return (T) Character.valueOf((char) ((Number) start).intValue()); } switch (prim.getName()) { case "int": return (T) (Object) ((Number) start).intValue(); case "long": return (T) (Object) ((Number) start).longValue(); case "short": return (T) (Object) ((Number) start).shortValue(); case "double": return (T) (Object) ((Number) start).doubleValue(); case "float": return (T) (Object) ((Number) start).floatValue(); case "byte": return (T) (Object) ((Number) start).byteValue(); case "boolean": return (T) (Object) (((Number) start).intValue() != 0 ? true : false); default: throw new IllegalArgumentException(prim.getName()); } } catch (Exception e) { e.printStackTrace(); } return (T) start; } }