Java Class Type Check isTypeConvertible(Class srcType, Class destType)

Here you can find the source of isTypeConvertible(Class srcType, Class destType)

Description

is Type Convertible

License

Open Source License

Declaration

public static boolean isTypeConvertible(Class srcType, Class destType) 

Method Source Code


//package com.java2s;
import java.util.*;

public class Main {
    private static List _numericPrimitiveClasses = Arrays
            .asList(new Class[] { Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE });
    private static List _numericWrapperClasses = Arrays
            .asList(new Class[] { Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class });

    public static boolean isTypeConvertible(Class srcType, Class destType) {
        // handle null: if srcType is null, then it represents
        // a null runtime value, and for our purposes it is type
        // convertible to any type that is assignable from Object.class
        if (srcType == null)
            return (Object.class.isAssignableFrom(destType));

        // check to see if the classes are assignable
        if (destType.isAssignableFrom(srcType))
            return true;

        // handle booleans: are we going from a wrapper Boolean
        // to a primitive boolean or vice-versa?
        if ((srcType == Boolean.TYPE || srcType == Boolean.class)
                && (destType == Boolean.TYPE || destType == Boolean.class))
            return true;

        // a numeric primitive or wrapper can be converted to
        // the same wrapper or a same or wider primitive.
        // handle chars specially
        int i = _numericPrimitiveClasses.indexOf(srcType);
        if (i < 0)
            i = _numericWrapperClasses.indexOf(srcType);

        int destP = _numericPrimitiveClasses.indexOf(destType);
        int destW = -1;
        if (destP < 0)
            destW = _numericWrapperClasses.indexOf(destType);

        // same size wrapper
        if (i >= 0 && destW == i)
            return true;

        // same or wider primitive
        if (i >= 0 && destP >= i)
            return true;

        // chars//from   www .j a  v  a2 s . c  om
        if (srcType == Character.class || srcType == Character.TYPE) {
            // chars: same size wrapper/primitive
            if (destType == Character.class || destType == Character.TYPE)
                return true;
        }

        // no other possibilities
        return false;
    }
}

Related

  1. isPrimitiveWrapper(Class type)
  2. isSimpleClass(Class clazz)
  3. isSimpleType(Class clazz)
  4. isSupportedParameter(Class type)
  5. isTerminal(Class clazz)
  6. isUniformCollection(Collection c, Class e)
  7. isWrapperOfPrimitiveType(Class primitiveType, Class otherType)
  8. isWrapperTypeOf(Class propertyType, Object propertyValue)