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
- cast(Class c)
- cast(Class extends T> c, Object o)
- cast(Class clazz, Object o, T def)
- cast(Class clazz, Object obj)
- cast(Class clazz, Object object)
- cast(Class toType, Object value)
- cast(Class type, Object key, Object value)
- cast(Class type, Object obj)
- cast(double[] arr)