A Generic Java Language Extension

The Generic Java Language

Why can't I cast to a parametrized type?

GJ does not admit casting to a parametrized type. It cannot do this
safely, since no run-time type information is maintained. But there
are situations where a type conversion from Object to a parameterized
type is essential, for instance when reading back serialized data.

This task can be solved using GJ's "raw types" feature.  The primary
purpose of raw types is to maintain backwards compatibility with
current Java. But the feature can also be exploited to achieve
casting, as follows:

Say, you have a variable


to which you wish to assign a value `y' of static type Object. Writing

  x = (Vector<String>) y

is illegal, since you cannot cast to a parameterized type. Instead you

  x = (Vector) y

The cast in the line above is legal, and yields a value of the raw
type `Vector'. The assignment of a value of a raw type to a variable
of a parameterized type is also legal, even though it will generate a
warning that the operation is unchecked. More information can be found
in the paper

  Making the future safe for the past:
  Adding Genericity to the Java Programming Language,

available from the "Documents" section on the GJ site.

Comments and bug reports to the Pizza Group,
pizza@cis.unisa.edu.au. Java is a trademark of Sun Microsystems. All software and documents on the Pizza site are © Copyright 1996, 1997 by the respective authors as attributed on each. Terms for redistribution are available.