Java Object Type Case cast(Class c, Object o)

Here you can find the source of cast(Class c, Object o)

Description

An implementation of Class#cast , which is unavailable prior to Java 5.0.

License

BSD License

Exception

Parameter Description
ClassCastExceptionIf the object cannot be cast to the given type.

Declaration

public static <T> T cast(Class<? extends T> c, Object o) throws ClassCastException 

Method Source Code

//package com.java2s;
/*BEGIN_COPYRIGHT_BLOCK*
    //w  w  w . j av a2s .  c o m
PLT Utilities BSD License
    
Copyright (c) 2007-2010 JavaPLT group at Rice University
All rights reserved.
    
Developed by:   Java Programming Languages Team
        Rice University
        http://www.cs.rice.edu/~javaplt/
    
Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:
    
- Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.
- Neither the name of the JavaPLT group, Rice University, nor the names of the library's 
  contributors may be used to endorse or promote products derived from this software without 
  specific prior written permission.
    
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    
*END_COPYRIGHT_BLOCK*/

public class Main {
    /**
     * <p>An implementation of {@link Class#cast}, which is unavailable prior to Java 5.0.  Unlike the
     * Java API method, this version allows a boxed value to be cast to its unboxed equivalent &mdash; for
     * example, {@code ReflectUtil.cast(int.class, 23)} will succeed (see SDN bug 6456930).</p>
     * 
     * <p>The method is only capable of checking that {@code o} is an instance of the class {@code c} &mdash; not 
     * that {@code o} is an instance of type {@code T} (for example, casting with a {@code Class<List<Integer>>} would 
     * only check that {@code o} is a {@code List<?>}, but the return type would by {@code List<Integer>}).
     * Such discrepancies are rare in practice, because class literals ({@code Foo.class}) will only produce classes
     * for which {@code T} is unparameterized or raw.</p>
     * 
     * <p>Following {@code Class.cast()}, a boxed type cannot be cast to its unboxed equivalent, despite the fact
     * that such a cast would be safe.  (From a practical point of view, we would prefer to avoid incurring the
     * overhead of {@link #box} on every cast.)</li>
     * </ul>
     * @throws ClassCastException  If the object cannot be cast to the given type.
     */
    public static <T> T cast(Class<? extends T> c, Object o) throws ClassCastException {
        if (box(c).isInstance(o)) {
            @SuppressWarnings("unchecked")
            T result = (T) o;
            return result;
        } else {
            throw new ClassCastException("Casting to " + c.getName() + " from " + o.getClass().getName());
        }
    }

    /** If {@code c} is a primitive type, return its boxed counterpart; otherwise, return {@code c}. */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> box(Class<T> c) {
        if (c.isPrimitive()) {
            if (c == Boolean.TYPE) {
                return (Class<T>) Boolean.class;
            }
            if (c == Character.TYPE) {
                return (Class<T>) Character.class;
            }
            if (c == Byte.TYPE) {
                return (Class<T>) Byte.class;
            }
            if (c == Short.TYPE) {
                return (Class<T>) Short.class;
            }
            if (c == Integer.TYPE) {
                return (Class<T>) Integer.class;
            }
            if (c == Long.TYPE) {
                return (Class<T>) Long.class;
            }
            if (c == Float.TYPE) {
                return (Class<T>) Float.class;
            }
            if (c == Double.TYPE) {
                return (Class<T>) Double.class;
            }
            if (c == Void.TYPE) {
                return (Class<T>) Void.class;
            }
        }
        return c;
    }

    /**
     * Produce a correctly-typed class corresponding to {@code obj}.  {@code obj.getClass()}, in contrast,
     * returns a {@code Class<?>}.
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<? extends T> getClass(T obj) {
        return (Class<? extends T>) obj.getClass();
    }
}

Related

  1. cast(B b0, Class cls)
  2. cast(byte b)
  3. cast(byte[] bytes)
  4. cast(Class c)
  5. cast(Class clazz, Object o, T def)
  6. cast(Class clazz, Object obj)
  7. cast(Class clazz, Object object)
  8. cast(Class targetClass, Object obj)