【发布时间】:2018-01-01 14:47:17
【问题描述】:
在我的项目中,我有一个这样的枚举:
public enum MyEnum {
FIRST(1),
SECOND(2);
private int value;
private MyEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static MyEnum fromValue(int value) {
for (MyEnum e : MyEnum.values()) {
if (e.getValue() == value) {
return e;
}
}
return null;
}
我有这个代码:
Map<String, Object> myMap = new HashMap<>();
// Fill my Map with data from database
myMap = namedParameterJdbcTemplate.queryForList(qry, paramsMap);
***if (Arrays.asList(MyEnum.values())
.contains(MyEnum.fromValue((int)
myMap.get("myKey")) )))*** {
// Do something
}
我得到了异常
java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.Integer** on this line : **if (Arrays.asList(MyEnum.values())
.contains(MyEnum.fromValue((int)myMap.get("myKey")) )))
myMap 填充了来自数据库的数据,知道它是一个 SQL Server 数据库并且 myKey > 从数据库返回的类型是数据库中的 tinyint。
你能告诉我我做错了什么吗? 谢谢。
问候。
【问题讨论】:
-
顺便说一下,
EnumSet.allOf(MyEnum.class)比 Arrays.asList(MyEnum.values()) 更有效(也更容易阅读)。请参阅the documentation 了解更多信息。 -
感谢您的评论,我会尝试的!
标签: java sql-server casting integer short