Thursday, 4 September 2008

Java Unchecked Cast Warning

An annoyance with Java that I had resently was with the unchecked cast warning. I had placed a String List in the HttpSession, but when I ready it back I got the warning "warning: [unchecked] unchecked cast"

I knew no error would occur, as I was setting the attribute in the HttpSession in the same servlet and I didn't want loads of warnings to build up, as this can hide real warnings I need to action.

So, my original code looked like

private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
List myItems = (ArrayList)session.getAttribute("myItems");
for (String myItem : myItems) {
...

I found that to stop the error appearing you can suppress the warning, by adding the SupressWarnings command anywhere before the line that gives the warning.

private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
@SuppressWarnings("unchecked")
List myItems = (ArrayList)session.getAttribute("myItems");
for (String myItem : myItems) {
...

Putting it just before the warning line, allows unexpected warnings before to still appear. But what about afterwards? In my case it wasn't necessary as the function had no more casts, but

private void foo(HttpServletRequest request) {
HttpSession session = request.getSession(true);
List myItems = null;
{
@SuppressWarnings("unchecked")
List uncheckedList = (ArrayList)session.getAttribute("myItems");
myItems = uncheckedList;
}
for (String myItem : myItems) {
...

Placing the SuppressWarnings in brackets keeps the suppression inside, so any unexpected warnings afterwards will still appear.

I think it depends on your code as to if you need to go this far or just leave it as I did, with SuppressWarnings just before the warning line, or even place it at the top of the package.

Where is best... You Decide.

No comments: