Raw Types


If you work with an existing system, written in J2SE 1.4 or earlier, it will use collection classes that do not support parameterization. You'll have plenty of code such as:

 List list = new ArrayList(); list.add("a"); 

You can still use this code under J2SE 5.0. When you use a generic type without binding it to a type parameter, you refer to the type as a raw type. The use of raw types is inherently not typesafe: You can add objects of any type to a raw collection and encounter runtime exceptions when retrieving an object of unexpected type. This is the fundamental reason why Sun introduced parameterized types.

Any such unsafe operation is met with a warning by the compiler. Using the default compiler options, the above two lines of code that add to a raw ArrayList result in the following compiler message:

 Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 

Do what the message says and recompile using the VM switch Xlint:unchecked:

 javac -source 1.5 -Xlint:unchecked *.java 

Under Ant, supply an additional nested element on the javac task:

 <target name="build" depends="init" description="build all">  <javac      srcdir="${src.dir}" destdir="${build.dir}"      source="1.5"      deprecation="on" debug="on" optimize="off" includes="**">    <classpath ref />    <compilerarg value="-Xlint:unchecked"/>  </javac> </target> 

Recompiling will present you with more specific details on the source of each unchecked warning:

 warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List       list.add("a");           ^ 

The Java compiler will generate an unchecked warning whenever it cannot guarantee the type safety of an operation on a parameterized type. If you are developing on an existing 1.4 or older application, you'll likely receive gobs of warnings. While it may not be possible or desirable to fix all the warnings at once, you should never treat warnings lightly. If you modify a section of legacy code, attempt to introduce generic types. You should be extremely leery of warnings that arise from any new code that you add.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net