Here you can find the source of cast(Class
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. |
public static <T> T cast(Class<T> clazz, Object o, T def)
//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); } }