Java Object Type Case cast(Object o, Class klass)

Here you can find the source of cast(Object o, Class klass)

Description

Cast an object savely.

License

GNU General Public License

Parameter

Parameter Description
T the target type
o the object to cast
klass the target class (same as T)

Return

null if o is null or the type o is not a subclass of klass. The casted value otherwise.

Declaration

@SuppressWarnings("unchecked")
public static <T> T cast(Object o, Class<T> klass) 

Method Source Code

//package com.java2s;
// License: GPL. For details, see LICENSE file.

public class Main {
    /**//from  w  w  w  .  j a va 2 s  . c  om
     * Cast an object savely.
     * @param <T> the target type
     * @param o the object to cast
     * @param klass the target class (same as T)
     * @return null if <code>o</code> is null or the type <code>o</code> is not
     *  a subclass of <code>klass</code>. The casted value otherwise.
     */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object o, Class<T> klass) {
        if (klass.isInstance(o)) {
            return (T) o;
        }
        return null;
    }
}

Related

  1. cast(int value)
  2. cast(long value)
  3. cast(Object inValue)
  4. cast(Object o)
  5. cast(Object o, Class clazz)
  6. cast(Object o, String clazz)
  7. cast(Object obj, Class clazz)
  8. cast(Object obj, Class type)
  9. cast(Object object)