tags:

views:

61

answers:

2

Is there any way I can change this code so I can remove the unchecked warning

ArrayList<String> keys = new ArrayList<String>();
// do some stuff then
// save keys in session
HttpServletRequest request = getThreadLocalRequest();
HttpSession session = request.getSession(true);
session.setAttribute(uuid, keys);

// get keys from session sometime later
@SuppressWarnings("unchecked")
ArrayList<String> keys = (ArrayList<String>) session.getAttribute(uuid);
+1  A: 

Well, you have to choose between:

  • Warning for raw type
  • Warning for unchecked conversion
  • Annotation to remove warning for raw type
  • Annotation to remove warning for unchecked conversion

The thing is that getAttribute() returns an Object, so the compiler does not know that that Object is an ArrayList<String>, so it's warning you that there will be problems in case that Object is not an ArrayList<String>.

You can de-parametrize ArrayList so it would accept a List of anything (so conversion is not needed, thus removing the warning for unchecked conversion), but then you get another warning for raw type.

pakore
+3  A: 

You can't. session.getAttribute() is type-unsafe.

You can create a wrapper method, so that you only have the @SuppressWarnings in one place:

public final class SessionUtils {
    @SuppressWarnings("unchecked")
    public static <T> T getSessionAttribute(HttpSession session, String name) {
        return (T) session.getAttribute(name);
    }
}

Then you can use, without warnings:

List<String> keys = SessionUtils.getAttribute(session, uuid);
Bozho
+1 for nice use of the T parameter. I guess that <T> is read from the assigned variable, right?
pakore
yes, it is inferred from context.
Bozho