Java Object Type Case cast(Class clazz, Object o, T def)

Here you can find the source of cast(Class clazz, Object o, T def)

Description

Try to cast an object to a specific class and returns a default value if it was impossible.

License

Open Source License

Parameter

Parameter Description
clazz the target class of the object.
o the casted object.
def the default value if the object couldn't be casted to the class.

Return

the casted object or the default value if the cast wasn't possible.

Declaration

public static <T> T cast(Class<T> clazz, Object o, T def) 

Method Source Code

//package com.java2s;
/*//from   ww w  . java 2  s.  co m
 * This file is part of Bukkit Plugin Utilities.
 * 
 * Bukkit Plugin Utilities is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 * 
 * Bukkit Plugin Utilities is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with Bukkit Plugin Utilities.
 * If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Try to cast an object to a specific class and returns a default value if
     * it was impossible.
     * 
     * @param clazz
     *            the target class of the object.
     * @param o
     *            the casted object.
     * @param def
     *            the default value if the object couldn't be casted to the
     *            class.
     * @return the casted object or the default value if the cast wasn't
     *         possible.
     * @since 1.0
     */
    public static <T> T cast(Class<T> clazz, Object o, T def) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return def;
        }
    }

    /**
     * Try to cast an object to a specific class and returns <code>null</code>
     * if it was impossible.
     * 
     * @param clazz
     *            the target class of the object.
     * @param o
     *            the casted object.
     * @return the casted object or <code>null</code> if the cast wasn't
     *         possible.
     * @since 1.0
     */
    public static <T> T cast(Class<T> clazz, Object o) {
        return cast(clazz, o, null);
    }
}

Related

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