Java Reference
In-Depth Information
Such a cast requires a run-time validity check. The check is performed as if the
cast had been a checked cast between |
S
| and |
T
|, as described below.
• The cast is a checked cast.
Such a cast requires a run-time validity check. If the value at run time is
null
, then
the cast is allowed. Otherwise, let
R
be the class of the object referred to by the
run-time reference value, and let
T
be the erasure (§
4.6
) of the type named in the
cast operator. A cast conversion must check, at run time, that the class
R
is assign-
Note that
R
cannot be an interface when these rules are first applied for any given
cast, but
R
may be an interface if the rules are applied recursively because the run-
time reference value may refer to an array whose element type is an interface type.
5.5.3. Checked Casts at Run Time
Here is the algorithm to check whether the run-time type
R
of an object is assignment com-
a run-time exception is thrown, it is a
ClassCastException
.
If
R
is an ordinary class (not an array class):
of
T
, or a run-time exception is thrown.
exception is thrown.
• If
T
is an array type, then a run-time exception is thrown.
If
R
is an interface:
thrown.
• If
T
is an interface type, then
R
must be either the same interface as
T
or a subinter-
face of
T
, or a run-time exception is thrown.
• If
T
is an array type, then a run-time exception is thrown.
If
R
is a class representing an array type
RC
[]
, that is, an array of components of type
RC
:
thrown.
• If
T
is an interface type, then a run-time exception is thrown unless
T
is the type
java.io.Serializable
or the type
Cloneable
(the only interfaces implemented by arrays).