Java Object Type Case cast(final Object obj, final Class type)

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

Description

Casts the given object to the specified type, or null if the types are incompatible.

License

Open Source License

Declaration

public static <T> T cast(final Object obj, final Class<T> type) 

Method Source Code

//package com.java2s;

public class Main {
    /**// w w  w  . j  ava  2s  . c  om
     * Casts the given object to the specified type, or null if the types are
     * incompatible.
     */
    public static <T> T cast(final Object obj, final Class<T> type) {
        if (!canCast(obj, type))
            return null;
        @SuppressWarnings("unchecked")
        final T result = (T) obj;
        return result;
    }

    /**
     * Checks whether objects of the given class can be cast to the specified
     * type.
     * 
     * @see #cast(Object, Class)
     */
    public static boolean canCast(final Class<?> c, final Class<?> type) {
        return type.isAssignableFrom(c);
    }

    /**
     * Checks whether the given object can be cast to the specified type.
     * 
     * @see #cast(Object, Class)
     */
    public static boolean canCast(final Object obj, final Class<?> type) {
        return canCast(obj.getClass(), type);
    }
}

Related

  1. cast(Class type, Object obj)
  2. cast(double[] arr)
  3. cast(final Class clazz)
  4. cast(final Number number, final Class returnType)
  5. cast(final Object o)
  6. cast(final Object object)
  7. cast(final Object original)
  8. cast(int value)
  9. cast(int value)