Java Reference
In-Depth Information
16.6. The
Field
Class
The
Field
class defines methods for asking the type of a field and for set-
ting and getting the value of the field. Combined with the inherited
Member
methods, this allows you to find out everything about the field declara-
tion and to manipulate the field of a specific object or class.
The
getGenericType
method returns the instance of
Type
that represents
the field's declared type. For a plain type, such as
String
or
int
, this
returns the associated
Class
object
String.class
and
int.class
, respect-
ively. For a parameterized type like
List<String>
, it will return a
Paramet-
erizedType
instance. For a type variable like
T
, it will return a
TypeVariable
instance.
The
getType
legacy method returns the
Class
object for the type of the
field. For plain types this acts the same as
getGenericType
. If the field's
declared type is a parameterized type, then
getType
will return the class
object for the erasure of the parameterized typethat is, the class object
for the raw type. For example, for a field declared as
List<String>
,
getType
will return
List.class
. If the field's declared type is a type variable, then
getType
will return the class object for the erasure of the type variable.
For example, given class
Foo<T>
, for a field declared with type
T
,
getType
would return
Object.class
. If
Foo
were declared as
Foo<Textends Number>
,
then
getType
would return
Number.class
.
You can ask whether a field is an enum constant using
isEnumConstant
.
You can also get and set the value of a field using the
get
and
set
meth-
ods. There is a general-purpose form of these methods that take
Object
arguments and return
Object
values, and more specific forms that deal
directly with primitive types. All of these methods take an argument spe-
cifying which object to operate on. For static fields the object is ignored
and can be
null
. The following method prints the value of a
short
field of
an object:
public static void printShortField(Object o, String name)
throws NoSuchFieldException, IllegalAccessException
{