Here you can find the source of cast(Class
@SuppressWarnings("unchecked") public static <T> T cast(Class<T> clazz, Object obj)
//package com.java2s; //License from project: Apache License public class Main { @SuppressWarnings("unchecked") public static <T> T cast(Class<T> clazz, Object obj) { if (clazz == null) throw new NullPointerException(); if (obj == null || clazz.isAssignableFrom(obj.getClass())) { return (T) obj; }/* w w w . ja v a 2 s.com*/ throw new ClassCastException(msgClassCastException(clazz, obj)); } private static String msgClassCastException(Class<?> clazz, Object obj) { return String.format("An instance of '%s' class is expected, but '%s'(class=%s) was given.", clazz.getName(), obj, obj == null ? null : obj.getClass().getName()); } }