src/main/java/net/balusc/util/ObjectConverter.java
@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);
    }
  }
@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.

@param from
The object value to be converted.
@param to
The type class which the given object should be converted to.
@return The converted object value.
@throws NullPointerException
If 'to' is null.
@throws UnsupportedOperationException
If no suitable converter can be found.
@throws RuntimeException
If conversion failed somehow. This can be caused by at least an
ExceptionInInitializerError, IllegalAccessException or
InvocationTargetException.