All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sql2o.converters.DefaultEnumConverterFactory Maven / Gradle / Ivy

There is a newer version: 0.2.6
Show newest version
package org.sql2o.converters;

/**
 * Default implementation of {@link EnumConverterFactory},
 * used by sql2o to convert a value from the database into an {@link Enum}.
 */
public class DefaultEnumConverterFactory implements EnumConverterFactory {
    public  Converter newConverter(final Class enumType) {
        return new Converter() {
            @SuppressWarnings("unchecked")
            public E convert(Object val) throws ConverterException {
                if (val == null) {
                    return null;
                }
                try {
                    if (val instanceof String){
                        return (E)Enum.valueOf(enumType, val.toString());
                    } else if (val instanceof Number){
                        return enumType.getEnumConstants()[((Number)val).intValue()];
                    }
                } catch (Throwable t) {
                    throw new ConverterException("Error converting value '" + val.toString() + "' to " + enumType.getName(), t);
                }
                throw new ConverterException("Cannot convert type '" + val.getClass().getName() + "' to an Enum");
            }

            public Object toDatabaseParam(Enum val) {
                return val.name();
            }
        };
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy