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

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

Description

cast

License

Apache License

Declaration

public static Object cast(Object val, Class type) throws ClassCastException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static Object cast(Object val, Class type) throws ClassCastException {
        if (val == null)
            return null;

        if (type == Boolean.class || type == Boolean.TYPE) {
            return ((Boolean) val).booleanValue();
        } else if (type == Character.class || type == Character.TYPE) {
            return ((Character) val).charValue();
        } else if (type == Byte.class || type == Byte.TYPE) {
            return ((Byte) val).byteValue();
        } else if (type == Short.class || type == Short.TYPE) {
            if (val instanceof Long)
                return ((Long) val).shortValue();
            else if (val instanceof Integer)
                return ((Integer) val).shortValue();
            else if (val instanceof Short)
                return ((Short) val).shortValue();
        } else if (type == Integer.class || type == Integer.TYPE) {
            if (val instanceof Long)
                return ((Long) val).intValue();
            else if (val instanceof Integer)
                return ((Integer) val).intValue();
        } else if (type == Long.class || type == Long.TYPE) {
            if (val instanceof Integer)
                return ((Integer) val).longValue();
            else if (val instanceof Long)
                return ((Long) val).longValue();
        } else if (type == Float.class || type == Float.TYPE) {
            if (val instanceof Double)
                return ((Double) val).floatValue();
            else if (val instanceof Float)
                return ((Float) val).floatValue();
        } else if (type == Double.class || type == Double.TYPE) {
            if (val instanceof Double)
                return ((Double) val).doubleValue();
            else if (val instanceof Float)
                return ((Float) val).doubleValue();
        } else if (type.isAssignableFrom(val.getClass())) {
            return type.cast(val);
        }/*from   ww  w . jav a  2s. c o m*/

        return null;
    }
}

Related

  1. cast(Object obj, Class clazz)
  2. cast(Object obj, Class type)
  3. cast(Object object)
  4. cast(Object object, Class targetClass)
  5. cast(Object source)
  6. cast(Object value, String sqlType)
  7. cast(Object x)
  8. cast(Object x)
  9. cast(Object[] parameters, Class[] types)