niryo niryo - 1 year ago 81
Java Question

java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.Integer

In my project I have an Enum like this :

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;
}


And I have this code :

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
}


I get the Exception

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 is filled with data from database, knowing that it is an SQL Server Database and that the myKey returned from database is of type tinyint in the database.

Can you please tell me what I am doing wrong ?
Thanks.

Regards.

Answer Source

java.lang.ClassCastException: java.lang.Short cannot be cast to java.lang.Integer

Here myMap.get("myKey") returns a Short instance but the returned declared object is Object as the map is declared Map<String, Object>.

It is as if you had written :

Object myValue = myMap.get("myKey")

Then you pass this Short object declared as Object to MyEnum.fromValue() that has as parameter an int.

MyEnum.fromValue((int)myValue));

The compiler tries so to cast the object to an Integer and then to unbox it into a int value.
But it is not an Integer but a Short.
The cast fails.

To solve your problem, you should first check the instance of your object.
If the object is not an instance of Short, you should throw an exception or ignore the value.
If it is, you should cast from Object to Short and pass this Short to fromValue() that will be automatically unboxed to short :

   Object myValue =  myMap.get("myKey");
   if (!(myValue instanceof Short)){          
      throw new YourRuntimeException("A Short is expected but get a " + myValue.getClass());
      // or ignore the value
   }

   if (Arrays.asList(MyEnum.values())
              .contains(MyEnum.fromValue(((short) myValue)) {
           ....
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download