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

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

Description

Casts an object to the class or interface represented by the targetClass Class object.

License

Open Source License

Parameter

Parameter Description
obj the object to be cast

Exception

Parameter Description
ClassCastException if the object is notnull and is not assignable to the type T.

Return

the object after casting, or null if obj is null

Declaration

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

Method Source Code

//package com.java2s;
/*/*from   ww w. ja  va 2 s.  c o m*/
 * JBoss, Home of Professional Open Source
 * Copyright 2007, Red Hat Middleware LLC, and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

public class Main {
    /**
     * Casts an object to the class or interface represented
     * by the targetClass <tt>Class</tt> object.
     * The ClassCastException thrown is more descriptive than
     * the original.
     *
     * @param obj the object to be cast
     * @return the object after casting, or null if obj is null
     *
     * @throws ClassCastException if the object is not
     * null and is not assignable to the type T.
     */
    public static <T> T cast(Class<T> targetClass, Object obj) {
        try {
            return targetClass.cast(obj);
        } catch (ClassCastException e) {
            assert obj != null : "a null can always be cast, it should never throw a ClassCastException";
            throw new ClassCastException("Unable to cast " + obj.getClass() + " to " + targetClass);
        }
    }
}

Related

  1. cast(Class c)
  2. cast(Class c, Object o)
  3. cast(Class clazz, Object o, T def)
  4. cast(Class clazz, Object obj)
  5. cast(Class clazz, Object object)
  6. cast(Class toType, Object value)
  7. cast(Class type, Object key, Object value)
  8. cast(Class type, Object obj)
  9. cast(double[] arr)