Java Object Type Case castSafe(Class inClass, Object inValue, T inDefault)

Here you can find the source of castSafe(Class inClass, Object inValue, T inDefault)

Description

cast Safe

License

Open Source License

Parameter

Parameter Description
inValue a parameter

Return

casted value or given default if would occur

Declaration

@SuppressWarnings("unchecked")
public static <T> T castSafe(Class<T> inClass, Object inValue, T inDefault) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from  w ww. ja v  a 2 s.co  m
     * @param inValue
     * @return casted value or given default if {@link ClassCastException} would
     *         occur
     */
    @SuppressWarnings("unchecked")
    public static <T> T castSafe(Class<T> inClass, Object inValue, T inDefault) {

        if (inClass == null) {
            throw new IllegalArgumentException("no target class specified");
        } else if (inValue != null && !inClass.isAssignableFrom(inValue.getClass())) {
            return inDefault;
        }

        try {

            return (T) inValue;

        } catch (Exception e) {

            return inDefault;
        }
    }

    /**
     * @param inValue
     * @return casted value or <code>null</code> if {@link ClassCastException}
     *         would occur
     */
    public static <T> T castSafe(Class<? extends T> inClass, Object inValue) {

        return castSafe(inClass, inValue, null);
    }
}

Related

  1. castOrDefault(Class type, Object value, T defaultValue, boolean allowNull)
  2. castOrDefault(Object o, Class type, T def)
  3. castOrNull(Object o, Class clazz)
  4. castOrNull(Object o, Class cls)
  5. castOrThrowError(Class clazz, T1 object, String messageTemplate)
  6. caststring1(String tmpq)
  7. castTo(Object o, Class cls)
  8. castToArray(Object object)
  9. castToClass_strict(Number valueIn, Class toClassIn)