现在我有一个简单的枚举名为 AppName
:
package misc.enumn.app;
import lombok.Getter;
import misc.enumn.BaseEnum;
/**
* @author dolphin
*/
@Getter
public enum AppName implements BaseEnum {
CRUISE( 1, "cruise"),
BACK(2, "back"),
;
private Integer key;
private String value;
AppName(Integer key, String value) {
this.key = key;
this.value = value;
}
public void setKey(Integer key) {
this.key = key;
}
public void setValue(String value) {
this.value = value;
}
public static AppName getAppMarkByValue(String value) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.name().equals(value)) {
datetimeType = type;
}
}
return datetimeType;
}
public static AppName getAppMarkByKey(Short key) {
AppName datetimeType = null;
for (AppName type : AppName.values()) {
if (type.key.equals(key)) {
datetimeType = type;
}
}
return datetimeType;
}
}
然后我定义一个请求对象,如下所示:
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserLoginRequest implements Serializable {
@ApiModelProperty(value = "app")
private AppName app;
}
当我将appid 1传递给服务器端时,服务器将appname解析为 BACK
,我不理解为什么它被解析为 BACK
不是“巡航”吗?我已经定义了枚举解析器:
public class IntegerCodeToEnumConverterFactory implements ConverterFactory<Integer, BaseEnum> {
private static final Map<Class, Converter> CONVERTERS = Maps.newHashMap();
@Override
public <T extends BaseEnum> Converter<Integer, T> getConverter(Class<T> targetType) {
Converter<Integer, T> converter = CONVERTERS.get(targetType);
if (converter == null) {
converter = new IntegerToEnumConverter<>(targetType);
CONVERTERS.put(targetType, converter);
}
return converter;
}
}
并添加到拦截器配置中:
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverterFactory(new IntegerCodeToEnumConverterFactory());
}
但似乎仍然无法解析枚举,我应该如何使其正确解析应用程序?这是错误的解析(我希望1解析为 CRUISE
和2被解析为 BACK
):
顺便说一下,当我将enum中的应用程序替换为整数时,它可以正确解析它(接收值1)。但我认为使用enum可能更易于阅读。
public class IntegerToEnumConverter <T extends BaseEnum> implements Converter<Integer, T> {
private Map<Integer, T> enumMap = Maps.newHashMap();
public IntegerToEnumConverter(Class<T> enumType) {
T[] enums = enumType.getEnumConstants();
for (T e : enums) {
enumMap.put(e.getKey(), e);
}
}
@Override
public T convert(Integer source) {
T t = enumMap.get(source);
if (ObjectUtils.isNull(t)) {
throw new IllegalArgumentException("");
}
return t;
}
}
暂无答案!
目前还没有任何答案,快来回答吧!