io.polaris.core.converter.EnumConverter Maven / Gradle / Ivy
package io.polaris.core.converter;
import io.polaris.core.lang.JavaType;
/**
* @author Qt
* @since 1.8
*/
public class EnumConverter> extends AbstractSimpleConverter {
private final JavaType targetType ;
public EnumConverter(Class enumClass) {
this.targetType = JavaType.of(enumClass);
}
@Override
public JavaType getTargetType() {
return targetType;
}
@Override
protected T doConvert(Object value, JavaType targetType) {
if (value == null) {
return null;
}
T[] enumConstants = targetType.getRawClass().getEnumConstants();
if (value instanceof Number) {
int i = ((Number) value).intValue();
return i >= 0 && i < enumConstants.length ? enumConstants[i] : null;
} else {
return (T) Enum.valueOf(targetType.getRawClass(), asString(value));
}
}
}