Java Object Type Case cast(Class clazz, Object obj)

Here you can find the source of cast(Class clazz, Object obj)

Description

cast

License

Apache License

Declaration

@SuppressWarnings("unchecked")
    public static <T> T cast(Class<T> clazz, Object obj) 

Method Source Code

//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());
    }
}

Related

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