4

I am wondering why the following issues a warning about an unsafe / unchecked operation:

Map<String, ProxySession> sessionMap = (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute");

Is the cast wrong? I can't understand what I am missing here.

P.S. I don't want to get rid of the warning, I want to understand the unsafe operation.

Thanks!

gpol
  • 916
  • 2
  • 17
  • 29
  • http://stackoverflow.com/questions/262367/type-safety-unchecked-cast http://stackoverflow.com/questions/509076/how-do-i-address-unchecked-cast-warnings http://stackoverflow.com/questions/2592642/type-safety-unchecked-cast-from-object – G_H Oct 18 '11 at 10:54

3 Answers3

6

It means that the cast will check that the returned object is a Map of some kind, but it won't be able to check anything about its contents, due to type erasure. At execution time, a map is a map is a map... so if someone put a Map<Integer, String> into your session instead, that line of code would still succeed. You'd only get an error when you tried to use one of the entries, e.g. by iterating over the entries and fetching the key and value.

Welcome to the wacky world of Java generics :(

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
1

It's an unchecked cast. You as a programmer may know that se.getSession() is expected to be of that exact type, with <String, ProxySession> parameters, so you're doing the cast, but it may not be of that exact type (the compiler suggests). Since you aren't programatically checking that, the compiler warns you.

See also: How do I address unchecked cast warnings?

Community
  • 1
  • 1
Alex Florescu
  • 4,787
  • 1
  • 26
  • 47
0

JVM doesn't check casts like this. For example, (Map<String, ProxySession>) se.getSession().getServletContext().getAttribute("myattribute"); will be equal to (Map) se.getSession().getServletContext().getAttribute("myattribute");

Pavel
  • 4,222
  • 7
  • 42
  • 67