org.simpleflatmapper.converter.impl.CharSequenceToEnumConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sfm-converter Show documentation
Show all versions of sfm-converter Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
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());
}
}