[e-lang] Type safety of Java generics

Constantine Plotnikov constantine.plotnikov at gmail.com
Wed May 30 09:04:54 EDT 2007


On 5/30/07, David Hopwood <david.hopwood at industrial-designers.co.uk> wrote:
>
> 'Doctor, it hurts when I use @SuppressWarnings.' ;-)
>
> Without @SuppressWarnings("unchecked"), this is what you get:
>
> >javac UnsafeGenerics2.java
> Note: UnsafeGenerics2.java uses unchecked or unsafe operations.
> Note: Recompile with -Xlint:unchecked for details.
>
> >javac -Xlint:unchecked UnsafeGenerics2.java
> UnsafeGenerics2.java:10: warning: [unchecked] unchecked cast
> found   : java.lang.Object
> required: java.util.ArrayList<java.lang.Integer>
>         ArrayList<Integer> b = (ArrayList<Integer>)(Object)a;
>                                                    ^
> 1 warning
>
Java Reflection generates classes in runtime that would not have been
cleanly compiled without SuppressWarnings anyway. They would not have
been compiled at all due to Java visibility rules anyway, so you could
assume that Reflection implies SupressWarnings.

> I think this is perfectly reasonable. It's claims such as this one
> by Sun that I object to:
>
> <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5105887>
>
> # Generics are supposed to be statically type safe.  However, in order
> # to interface with old code and to allow programs which cannot be
> # expressed type safely in the current language, we sometimes allow
> # unsafe expressions but give mandatory warnings (they are required by
> # the language specification).  This means that we can give a type
> # safety guarantee:
> #
> # "if your entire application has been compiled without unchecked
> # warnings using javac -source 1.5, it is type safe."
>
<nitpicking-mode>Note that they do not say that SuppressWarnings
should not be used. They say that the program should compile without
warnings. And there will be no warnings if SuppressWarnings is used
directly or indirectly (as with reflection). So their statement is
falser than it looks on the first sight.</nitpicking-mode>.

> There is no such guarantee. (Mutable covariant arrays are another reason
> why not, but at least the fact that array mutation can fail at runtime
> is well-known by Java programmers; the interactions between generics and
> reflection are not.)
>
Considering that it is almost impossible to write a program without
using SuppressWarnings in strategic places (you could try to store an
ArrayList in HTTP session to have some fun), SuppressWarnings is an
expected way of using generics. A the note about statical safety would
have borne only limited theoretical value even if it were true.

Constantine


More information about the e-lang mailing list