views:

247

answers:

3

Is there any Java compiler flag that one can pass to tell the compiler to disallow the use of raw types? That is, for any generic class, let the compiler force that the parameterized version be used, and throw a compilation error otherwise?

+4  A: 

You can configure the use of raw types within Eclipse to be a warning or an error.

It's under Preferences / Java / Compiler / Errors and Warnings / Generic types / Usage of a raw type.

javac doesn't have anything like this as far as I'm aware - even with -Xlint:all you don't get a warning for something like:

ArrayList x = new ArrayList();
Jon Skeet
You should get a warning from JDK7 (b38).
Tom Hawtin - tackline
(Although I believe Eclipse defaults to the JDT(?) compiler.)
Tom Hawtin - tackline
+4  A: 

You can get it to warn you via:

-Xlint:unchecked

This will generate warning in some, but not all, cases of missing generics.

import java.util.ArrayList;
import java.util.List;

public class Main
{
    public static void main(final String[] argv)
    {
        List list = new ArrayList(); // no warning at all

        list.add("Hello"); // warning will be on this line
    }
}

Given the warning you can then go back and fix up the code to add the generics to the declarations.

Not ideal, and if I remember right it still won't catch everything.

TofuBeer
+6  A: 

JDK7 (b38) introduces -Xlint:rawtypes. As mentioned above, -Xlint:unchecked warns about unchecked conversions.

Maurizio Cimadamore of the javac team wrote a weblog entry about it.

Tom Hawtin - tackline
Both of the links point to the bug database entry.
Michael Myers
Tom Hawtin - tackline
Unfortunately it also warns about 'instanceof List' and 'Class<List>', which it should not.http://mail.openjdk.java.net/pipermail/compiler-dev/2008-November/000711.html
Kevin Bourrillion