org.springframework.core.convert.support.StringToEnumConverter Maven / Gradle / Ivy
package org.springframework.core.convert.support;
import java.util.EnumSet;
import java.util.Set;
import org.springframework.boot.bind.RelaxedNames;
import org.springframework.core.convert.converter.Converter;
@SuppressWarnings("rawtypes")
public class StringToEnumConverter implements Converter {
private final Class enumType;
public StringToEnumConverter(Class enumType) {
this.enumType = enumType;
}
@SuppressWarnings("unchecked")
@Override
public T convert(String source) {
if (source.isEmpty()) {
return null;
}
source = source.trim();
for (T candidate : (Set) EnumSet.allOf(this.enumType)) {
RelaxedNames names = new RelaxedNames(candidate.name().replace('_', '-').toLowerCase());
for (String name : names) {
if (name.equals(source)) {
return candidate;
}
}
if (candidate.name().equalsIgnoreCase(source)) {
return candidate;
}
}
throw new IllegalArgumentException("No enum constant " + this.enumType.getCanonicalName() + "." + source);
}
}