@ SuppressWarnings ( "unchecked" ) public static < T > T convert ( Object from , Class < T > to ) { // Null is just null. if ( from == null ) { return null ; } // Can we cast? Then just do it. if ( to . isAssignableFrom ( from . getClass ( ) ) ) { return to . cast ( from ) ; } // Lookup the suitable converter. String converterId = from . getClass ( ) . getName ( ) + "_" + to . getName ( ) ; Method converter = CONVERTERS . get ( converterId ) ; if ( converter == null ) { throw new UnsupportedOperationException ( "Cannot convert from " + from . getClass ( ) . getName ( ) + " to " + to . getName ( ) + ". Requested converter does not exist." ) ; } // Convert the value. try { // primitives don't appear to have a .cast() method, which causes a null // pointer exception if ( to . isPrimitive ( ) ) { return ( T ) converter . invoke ( to , from ) ; } return to . cast ( converter . invoke ( to , from ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Cannot convert from " + from . getClass ( ) . getName ( ) + " to " + to . getName ( ) + ". Conversion failed with " + e . getMessage ( ) , e ) ; } }
Convert the given object value to the given class .