Java Reference
In-Depth Information
Field field = o.getClass().getField(name);
short value = (Short) field.get(o);
System.out.println(value);
}
The return value of
get
is whatever object the field references or, if the
field is a primitive type, a wrapper object of the appropriate type. For
our
short
field,
get
returns a
Short
object that contains the value of the
fieldthat value is automatically unboxed for storing in the local variable
value
.
The
set
method can be used in a similar way. A method to set a
short
field to a provided value might look like this:
public static void
setShortField(Object o, String name, short nv)
throws NoSuchFieldException, IllegalAccessException
{
Field field = o.getClass().getField(name);
field.set(o, nv);
}
Although set takes an
Object
parameter, we can pass a
short
directly and
let a boxing conversion wrap it in a
Short
object.
If the field of the specified object is not accessible and access control
is being enforced, an
IllegalAccessException
is thrown. If the passed ob-
ject does not have a type that declares the underlying field, an
Illeg-
alArgumentException
is thrown. If the field is non-static and the passed
object reference is
null
, a
NullPointerException
is thrown. Accessing a
static field can require initializing a class, so it is also possible for an
Ex-
ceptionInInitializerError
to be thrown.
The
Field
class also has specific methods for getting and setting prim-
itive types. You can invoke
get
PrimitiveType
and
set
PrimitiveType
on a