Java Reference
In-Depth Information
FIGURE 4.3 The inheritance tree for contexts.
An
IDefn
is the interface type for symbol table definitions, which has two implementa-
tions:
1. A
TypeNameDefn
, which defines a type name. An
IDefn
of this sort encapsulates the
Type
that it denotes.
2. A
LocalVariableDefn
defines a local variable and encapsulates the name, its
Type
,
and an offset in the current run-time stack frame. (We discuss stack frame offsets in
Section 4.5.2.)
4.3.2 Finding Method and Field Names in Type Objects
As we discussed in Section 4.2.3, the types defined by classes are represented in the same
way as they are in the Java library, so that we may consistently manipulate types that we
define and types that we import.
Class member (field and method in j--) names are not declared in a
ClassContext
,
but in the
Types
that they declare. We rely on the encapsulated
Class
object to store the
interface information, and we rely on Java reflection to query a type for information about
its members.
For example,
Type
supports a method
fieldFor()
that, when given a name, returns
a
Field
with the given name that is defined for that type. It delegates the finding of this
field to a search of the underlying
Class
object and can be seen from the code that defines
fieldFor()
:
publicFieldfieldFor(Stringname){
Class<?>cls=classRep;
while(cls!=null){
java.lang.reflect.Field[]fields=
cls.getDeclaredFields();
for(java.lang.reflect.Fieldfield:fields){
if(field.getName().equals(name)){
returnnewField(field);
}
}
cls=cls.getSuperclass();
}
returnnull;
}
This code first looks for the named field in the
Class
object for the
Type
being defined. If it
does not find it there, it looks in the
Class
object for the
Type
's super type, and so on until
either the field is found or we come to the base of the inheritance tree, in which case
null
is
returned to indicate that no such field was found. If we find the
java.lang.reflect.Field
,
Search WWH ::
Custom Search