2.7 Checking for Lint
Several times in this chapter, you've heard about lint warnings, which
sounds more like something you get out of a dryer than a compiler. These
warnings are a new feature of Tiger, though, and important in figuring
out how to really bulletproof your code.
2.7.1 How do I do that?
Take a simple piece of code that used a type that can be parameterized,
but without type parameters:
private List getList( ) {If you compile this in Tiger, with the -source 1.5 flag, you'll get this
List list = new LinkedList( );
list.add(3);
list.add("Blind");
list.add("Mice");
return list;
}
message:NOTEYou can compile all
of the examples
for this book with
"-Xlint:unchecked"
by using the Ant
target "compilecheck".
Note: GenericsTester.java uses unchecked or unsafe operations.If you recompile with the suggested flag, you are telling the compile to
Note: recompile with -Xlint:unchecked for details.
show lint warnings (-Xlint), and specifically to show those warnings
that are unchecked. .
Here's some sample output with these warnings turned on:
[javac] code\src\com\oreilly\tiger\ch02\GenericsTester.java:63: warning:These warnings indicate that the compiler isn't able to ensure that the
[unchecked] unchecked call to add(E) as a member of
the raw type java.util.List
[javac] list.add(3);
[javac] ^
[javac] src\com\oreilly\tiger\ch02\GenericsTester.java:64: warning:
[unchecked] unchecked call to add(E) as a member of
the raw type java.util.List
[javac] list.add("Blind");
[javac] ^
[javac] src\com\oreilly\tiger\ch02\GenericsTester.java:65: warning:
[unchecked] unchecked call to add(E) as a member of
the raw type java.util.List
[javac] list.add("Mice");
[javac] ^
[javac] 3 warnings
values added to the list (named list in this case) are the intended type.
That's because list wasn't parameterized.You can get rid of these warnings by specifying a type in your List construction:
private List getList( ) {NOTEAutoboxing is
List<Object> list = new LinkedList<Object>( );
list.add(3);
list.add("Blind");
list.add("Mice");
return list;
}
covered in
Chapter 4.While this doesn't do much for type-safety, it does take care of the warnings,
as the types being added to list are all of type Object (the literal 3
is autoboxed to an Integer, which is of course an Object).
2.7.2 What about...
NOTEAnnotations are
covered in
Chapter 6....annotations? For those of you who may be ahead on Tiger, there is an
annotation,
called SuppressWarnings, which allows you to keep these
warnings from showing up in a compilation using -source 1.5. You can
also just recompile under Java 1.4, although that's obviously a pretty
shortsighted solution. The best choice, if at all possible, is to parameterize
your generic types, and enforce type-safety whenever possible.