Whizu

jQuery Mobile in Java

View project on GitHub
Whizu Download
jQuery Mobile widgets
Pages Accordions Buttons Collapsibles
Check out my latest project at www.whizu.me and stop typing passwords with Kee Password Manager. Just like that.

How to avoid unchecked cast warnings with Java Generics

Written by Rudy D'hauwe on August 10, 2013.

If you've ever made a serious effort to get rid of unchecked warnings from the Java compiler then you'll probably have found some cases where you know a cast is unavoidable yet correct but you can't convince the compiler of it. Is there anything better than adding the @SuppressWarnings(“unchecked”) annotation around the whole method?

The problem with the @SuppressWarnings solution is that it suppresses warnings for the whole method, even though it's just one little cast that you want to allow. What if there's another place in the method where the compiler would have given a warning, telling you about a real problem? There's also a readability problem. If it's a big method, it can be hard to work out which particular line is the reason for the @SuppressWarnings annotation; you would have to add a comment indicating where the unchecked cast warning originates.

Personally I have found the following to be a nice solution.

Suppose you have the following.

List list = (List) x;

I changed it into this.

import org.whizu.util.Objects;

List list = Objects.cast(x);

The cast method is defined like this.

package org.whizu.util;

public class Objects {

    @SuppressWarnings("unchecked")
    public static  T cast(Object obj) {
        return (T) obj;
    }
}

The static method in the utility class also allows to write the following.

import static org.whizu.util.Objects.cast;

List list = cast(x);

This cast technique is basically a way to move all of the @SuppressWarnings annotations from your code to single place. You should still follow the same guidelines as you would have without cast. It should only be used as a last resort if you can't restructure your code to eliminate the warnings. And you must be really sure that the value being cast really is of the type you are casting it to. Otherwise you will get a ClassCastException at some completely different part of your code, where there might not even be an explicit cast.

Written by Rudy D'hauwe | Copyright © 2013-2014 | All rights reserved.