20030113 Monday January 13, 2003

ConvertUtils problem solved! I got the solution to my ConvertUtils problem from the hibernate-devel mailing list. Thanks to Juozas Baliuka! Here's my new convert method:

public Object convert(Class type, Object value) {
    if (log.isDebugEnabled()) {
        log.debug("entering 'convert' method");
    }

    // for a null value, return null
    if (value == null) {
        return null;
    } else if (value.getClass().isAssignableFrom(type)) {
        return value;
    } else if (ArrayList.class.isAssignableFrom(type)
                   && (value instanceof Collection)) {
        return new ArrayList((Collection) value); // List, Set, Collection  -> ArrayList
    } else if (type.isAssignableFrom(Collection.class)
                   && (value instanceof Collection)) {
        try {
            //most of collections implement this constructor
            Constructor constructor =
                type.getConstructor(new Class[] { Collection.class });

            return constructor.newInstance(new Object[] { value });
        } catch (Exception e) {
            log.error(e);
        }
    }

    throw new ConversionException("Could not convert "
                                  + value.getClass().getName() + " to "
                                  + type.getName() + "!");
}

Posted in Java at Jan 13 2003, 09:15:09 AM MST Add a Comment