Home > OS >  Cast safely a sessionScope value in Java
Cast safely a sessionScope value in Java

Time:01-17

I have a Map object stored in a sessionScope. If I cast it to the following object:

Map<String,Object> mapItem = (Map<String, Object>) entry.getValue();

I get a Type safety warning. Type safety:

Unchecked cast from Object to Map<String,Object>

I tried to cast the scope variable to an object and check what instance the object is but then I can not directly check if it is of Map<String,Object>. So I wonder how I should handle this further?

Object obj = entry.getValue();
if(obj instanceof Map<?, ?>) {
    //not sure what to do here
}

Any help is highly appreciated!

CodePudding user response:

I think the issue is with the generics applied to the original Map your Entry is from. Consider these examples

Map<String, Object> map = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
    Map<String, Object> mapItem = (Map<String, Object>) entry.getValue(); // Will have unchecked warning
}

// Declare another map specifying the values type more specifically
Map<String, Map<String, Object>> map2 = new HashMap<>();
for (Map.Entry<String, Map<String, Object>> entry : map2.entrySet()) {
    Map<String, Object> mapItem = entry.getValue(); // Will not require cast
}

The issue occurs because the compiler doesn't know anything more about the values type than its an Object. You know its a Map<String, Object> so you can tell the compiler that with generics and it will enforce that in the rest of the code.

CodePudding user response:

It's not easy to achieve that; Look at how to handle it in Gson:

 Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
 new Gson().fromJson("{}", mapType);
  •  Tags:  
  • Related