Java Reference
In-Depth Information
The use of raw types is allowed only as a concession to compatibility of legacy code. The
use of raw types in code written after the introduction of generics into the Java program-
ming language is strongly discouraged. It is possible that future versions of the Java pro-
gramming language will disallow the use of raw types.
To make sure that potential violations of the typing rules are always flagged, some accesses
to members of a raw type will result in compile-time unchecked warnings. The rules for
compile-time unchecked warnings when accessing members or constructors of raw types
are as follows:
• At an assignment to a field: if the type of the left-hand operand is a raw type, then
a compile-time unchecked warning occurs if erasure changes the field's type.
• At an invocation of a method or constructor: if the type of the class or interface to
search (§ 15.12.1 ) is a raw type, then a compile-time unchecked warning occurs if
erasure changes any of the formal parameter types of the method or constructor.
• No compile-time unchecked warning occurs for a method call when the formal
parameter types do not change under erasure (even if the result type and/or throws
clause changes), for reading from a field, or for a class instance creation of a raw
type.
Note that the unchecked warnings above are distinct from the unchecked warn-
ings possible from unchecked conversion (§ 5.1.9 ) , casts (§ 5.5.2 ), method de-
clarations (§ 8.4.1 , § 8.4.8.3 , § 8.4.8.4 , § 9.4.1.2 ), and variable arity method in-
vocations (§ 15.12.4.2 ) .
The warnings here cover the case where a legacy consumer uses a generified
library. For example, the library declares a generic class Foo<T extends String>
that has a field f of type Vector<T> , but the consumer assigns a vector of integers
to e .f where e has the raw type Foo . The legacy consumer receives a warning
because it may have caused heap pollution (§ 4.12.2 ) for generified consumers
of the generified library.
(Note that the legacy consumer can assign a Vector<String> from the library to
its own Vector variable without receiving a warning. That is, the subtyping rules
4.10.2 ) of the Java programming language make it possible for a variable of
a raw type to be assigned a value of any of the type's parameterized instances.)
The warnings from unchecked conversion cover the dual case, where a generi-
fied consumer uses a legacy library. For example, a method of the library has
the raw return type Vector , but the consumer assigns the result of the method in-
vocation to a variable of type Vector<String> . This is unsafe, since the raw vector
might have had a different element type than String , but is still permitted us-
Search WWH ::




Custom Search