@ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public static Object convert ( Object source , Class < ? > target ) throws ConversionException { if ( target == null ) { throw new ConversionException ( "Unable to perform conversion, target was null" ) ; } if ( source == null ) { if ( target . isPrimitive ( ) ) { throw new ConversionException ( String . format ( "Unable to convert null to primitive value of %s" , target ) ) ; } return source ; } else if ( ( source instanceof Float && ( ( Float ) source ) . isNaN ( ) ) || ( source instanceof Double && ( ( Double ) source ) . isNaN ( ) ) ) { // Don't convert NaN values return source ; } // if (BaseConnection.class.isAssignableFrom(source.getClass()) && !target.equals(IConnection.class)) { // log.debug("Conversion failure - source: {} target: {}", source.getClass(), target); // throw new ConversionException("Source is not assignable and target is not equal to IConnection"); // } if ( target . isInstance ( source ) ) { return source ; } if ( target . isAssignableFrom ( source . getClass ( ) ) ) { return source ; } if ( target . isArray ( ) ) { return convertToArray ( source , target ) ; } if ( target . equals ( String . class ) ) { return source . toString ( ) ; } if ( target . isPrimitive ( ) ) { return convertToWrappedPrimitive ( source , primitiveMap . get ( target ) ) ; } if ( wrapperMap . containsKey ( target ) ) { return convertToWrappedPrimitive ( source , target ) ; } if ( target . equals ( Map . class ) ) { return convertBeanToMap ( source ) ; } if ( target . equals ( List . class ) || target . equals ( Collection . class ) ) { if ( source . getClass ( ) . equals ( LinkedHashMap . class ) ) { return convertMapToList ( ( LinkedHashMap < ? , ? > ) source ) ; } else if ( source . getClass ( ) . isArray ( ) ) { return convertArrayToList ( ( Object [ ] ) source ) ; } } if ( target . equals ( Set . class ) && source . getClass ( ) . isArray ( ) ) { return convertArrayToSet ( ( Object [ ] ) source ) ; } if ( target . equals ( Set . class ) && source instanceof List ) { return new HashSet ( ( List ) source ) ; } if ( source instanceof Map ) { return convertMapToBean ( ( Map ) source , target ) ; } throw new ConversionException ( String . format ( "Unable to preform conversion from %s to %s" , source , target ) ) ; }
Convert source to given class