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

org.simpleflatmapper.converter.impl.CharSequenceToEnumConverter Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

The newest version!
package org.simpleflatmapper.converter.impl;

import org.simpleflatmapper.converter.Context;
import org.simpleflatmapper.converter.ContextualConverter;

public class CharSequenceToEnumConverter> implements ContextualConverter {
    private final Class enumClass;
    private final E[] values;

    public CharSequenceToEnumConverter(Class enumClass) {
        this.enumClass = enumClass;
        this.values = enumClass.getEnumConstants();
    }

    @Override
    public E convert(CharSequence in, Context context) throws Exception {
        if (in == null || in.length() == 0) return null;
        
        char c = in.charAt(0);
        if (Character.isDigit(c)) {
            int i = Integer.parseInt(in.toString());
            if (i < 0 || i >= values.length) {
                throw new IllegalArgumentException("Invalid ordinal value " + in  + " for " + enumClass);
            }
            return values[i];
        }
        
        return Enum.valueOf(enumClass, in.toString());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy