Java Reference
In-Depth Information
3. The following table summarizes other casts. In reading the table, think of the rows as
Type 1 and the columns as Type 2 . So the table says whether or not (and how) a type
labeling a row may be cast to a type labeling a column.
boolean char int BooleanCharacterInteger
boolean Identity
Error
Error
Boxing
Error
Error
char Error
Identity
Widening
Error
Boxing
Error
int Error
Narrowing
Identity
Error
Error
Boxing
Boolean Unboxing
Error
Error
Identity
Error
Error
Character Error
Unboxing
Error
Error
Identity
Error
Integer Error
Error
Unboxing
Error
Error
Identity
(a) A boolean can always be cast to a Boolean . The Boolean simply encapsulates
the boolean value so the operation is called boxing. Similarly, a char can be
boxed as a Character , and an int can be boxed as an Integer .
(b) A Boolean can be cast to a boolean using unboxing, plucking out the encapsu-
lated boolean value. Similarly for Character s and Integer s.
(c) One primitive type may often be cast to another. For example, a char may be
cast to an int . This is an example of widening and requires no run-time action.
An int may be cast to a char . This is an example of narrowing and requires the
execution of the i2c instruction at run-time.
(d) Some types may not be cast to other types. For example, one may not cast a
boolean to an int . Such casts are invalid.
The code for analyze() in JCastOp follows:
publicJExpressionanalyze(Contextcontext){
expr=(JExpression)expr.analyze(context);
type=cast=cast.resolve(context);
if(cast.equals(expr.type())){
converter=Converter.Identity;
}elseif(cast.isJavaAssignableFrom(expr.type())){
converter=Converter.WidenReference;
}elseif(expr.type().isJavaAssignableFrom(cast)){
converter=newNarrowReference(cast);
}elseif((converter=
conversions.get(expr.type(),cast))!=null){
}else{
JAST.compilationUnit.reportSemanticError(line,
"Cannotcasta"+expr.type().toString()+"toa"
+cast.toString());
}
returnthis;
}
In the code, cast is the type that we want to cast the expression expr to. The code not
only decides whether or not the cast is valid, but if it is valid, computes the Converter that
will be used at code generation time to generate any run-time code required for the cast. If
no such converter is defined, then the cast is invalid.
One example of a converter is that for narrowing one reference type to another (more
specific) reference sub-type; the converter is NarrowReference and its code is as follows:
classNarrowReferenceimplementsConverter{
privateTypetarget;
Search WWH ::




Custom Search