Apparently this special code for using
template makes the return of
getFromSessionMap a variable type and
hence no need for a cast.
Fundamentally, there has to be a typecast somewhere between getting the result of session.getAttribute(sessionKey) and the assignment to MyClassType. The Java language (and the JVM) will not allow some object that is not a MyClassType instance (or a subtype thereof) to be assigned to a MyClassType variable.
No matter how you write the code, a typecast has to occur. And since the attribute (apparently) is not a MyClassType (or subtype), you are getting a ClassCastException.
So the real question is why aren't you getting a compilation error? And the answer is the @SuppressWarnings("unchecked")! If you removed that warning, you would get an "unsafe type conversion" error message for this line:
return (T) session.getAttribute(sessionKey);
In truth, Java cannot do a (real) type cast to a generic type. And that is what the warning / error message is there to point out. In fact, once the code has been compiled, this code
public <T> T getFromSessionMap(String sessionKey) {
return (T)session.getAttribute(sessionKey);
}
is actually no different in meaning from this:
public Object getFromSessionMap(String sessionKey) {
return session.getAttribute(sessionKey);
}
Technically speaking this is called "type erasure".
So where is the type checking / typecast actually occurring? The answer is in this line:
MyClassType type = request.getFromSessionMap("abc");
Even though you haven't written a typecast here, the code generated by the Java compiler does a typecast before assigning the value to type. It has to. Because as far as it knows, the instance it is assigning could be any object type.
Other posters have suggested adding a Class argument to getFromSessionMap. By itself this does absolutely nothing. If you also replace the body of the method with:
return clazz.cast(session.getAttribute(sessionKey));
you will cause the method to actually do a real type check. But this only cause ClassCastException to be thrown at a different place. And the assignment statement will still do a hidden type cast!!