alasdair.info

Friday, August 31, 2007

SuppressWarnings annotation in Java

I work with a lot of code written prior to Java 5 and the introduction of generics. As a result there are lots of methods that return things like a java.util.List. The type of the objects in this list are all the same. So for example it is a java.util.List, but the method does not say that. As a result you might want to write the following code:

List myStringList = getList();

where getList is defined as:

public List getList();

this results in a warning because a List is not a List so it is potentially unsafe. In these cases the SuppressWarnings annotation can be used. Typically you would have something like this:

@SuppressWarnings("unchecked")
public void myMethod()
{
// some code

List myStringList = getList();

// some more code
}


the problem with this is that is suppresses uncheck warnings for the whole method. Fortunately suppress warnings can be used right by the definition of myStringList, for example:

public void myMethod()
{
// some code

@SuppressWarnings("unchecked")
List myStringList = getList();

// some more code
}


at which point it only applies to the line that declares myStringList. It is important to note that this only works when you define and assign to a variable, you cannot do:

@SuppressWarnings("unchecked")
myStringList = getList();


This is seriously cool.
Alasdair

No comments: