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-
ment compatible with the type T , via the algorithm in § 5.5.3 .
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-
patible with the type T which is the erasure (§ 4.6 ) of the type named in the cast operator. If
a run-time exception is thrown, it is a ClassCastException .
If R is an ordinary class (not an array class):
• If T is a class type, then R must be either the same class (§ 4.3.4 ) as T or a subclass
of T , or a run-time exception is thrown.
• If T is an interface type, then R must implement (§ 8.1.5 ) interface T , or a run-time
exception is thrown.
• If T is an array type, then a run-time exception is thrown.
If R is an interface:
• If T is a class type, then T must be Object 4.3.2 ), or a run-time exception is
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 :
• If T is a class type, then T must be Object 4.3.2 ), or a run-time exception is
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).
Search WWH ::




Custom Search