Java Object Type Case castOrNull(Object o, Class cls)

Here you can find the source of castOrNull(Object o, Class cls)

Description

Cast object to class or return null.

License

LGPL

Parameter

Parameter Description
o The object to cast
cls The class to cast o to

Return

o cast as cls. null if o is null or not a instance of cls.

Declaration

public static <T> T castOrNull(Object o, Class<T> cls) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    /**/*  www  . j a  v  a2 s.c om*/
     * Cast object to class or return null.
     * @param o The object to cast
     * @param cls The class to cast o to
     * @return o cast as cls. null if o is null or not a instance of cls.
     */
    public static <T> T castOrNull(Object o, Class<T> cls) {
        if (o == null)
            return null;
        if (cls.isInstance(o))
            return cls.cast(o);
        return null;
    }
}

Related

  1. castObject(Object fromObj, Class toClass)
  2. castObject(Object ob)
  3. castOrDefault(Class type, Object value, T defaultValue, boolean allowNull)
  4. castOrDefault(Object o, Class type, T def)
  5. castOrNull(Object o, Class clazz)
  6. castOrThrowError(Class clazz, T1 object, String messageTemplate)
  7. castSafe(Class inClass, Object inValue, T inDefault)
  8. caststring1(String tmpq)
  9. castTo(Object o, Class cls)