BJB
BJB

Reputation: 153

how to remove SuppressWarnings("unchecked")

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

Upvotes: 3

Views: 2282

Answers (2)

Bozho
Bozho

Reputation: 597056

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

Upvotes: 8

pakore
pakore

Reputation: 11497

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.

Upvotes: 2

Related Questions