Java Object Type Case cast(Class type, Object obj)

Here you can find the source of cast(Class type, Object obj)

Description

Cast an object type to the specified type.

License

Open Source License

Parameter

Parameter Description
type A class that indicates the target type.
obj An object to be casted.
T The target type.

Return

A casted object if the given object can be casted to the specified type. Otherwise null .

Declaration

public static <T> T cast(Class<T> type, Object obj) 

Method Source Code

//package com.java2s;
/*/*  w  w  w. j  a  v a2s .c o  m*/
 * Copyright (c) 2014-2015 NEC Corporation
 * All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this
 * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
 */

public class Main {
    /**
     * Cast an object type to the specified type.
     *
     * @param type  A class that indicates the target type.
     * @param obj   An object to be casted.
     * @param <T>   The target type.
     * @return  A casted object if the given object can be casted to the
     *          specified type. Otherwise {@code null}.
     */
    public static <T> T cast(Class<T> type, Object obj) {
        return (type.isInstance(obj)) ? type.cast(obj) : null;
    }
}

Related

  1. cast(Class clazz, Object obj)
  2. cast(Class clazz, Object object)
  3. cast(Class targetClass, Object obj)
  4. cast(Class toType, Object value)
  5. cast(Class type, Object key, Object value)
  6. cast(double[] arr)
  7. cast(final Class clazz)
  8. cast(final Number number, final Class returnType)
  9. cast(final Object o)