Java Reference
In-Depth Information
•
float getFloat(Object object)
returns the value of the floating-
point field for the specified
object
.
•
int getInt(Object object)
returns the value of the integer field for
the specified
object
.
•
long getLong(Object object)
returns the value of the long integer
field for the specified
object
.
•
short getShort(Object object)
returnsthevalueoftheshortinteger
field for the specified
object
.
get()
returns the value of any type of field. In contrast, the other listed methods
returnthevaluesofspecifictypesoffields.Thesemethodsthrow
NullPointerEx-
ception
when
object
is
null
and the field is an instance field,
IllegalAr-
gumentException
when
object
is not an instance of the class or interface de-
claringtheunderlyingfield(ornotaninstanceofasubclassorinterfaceimplementor),
and
IllegalAccessException
when the underlying field cannot be accessed (it
is private, for example).
void setInt(Object obj, int i)
counterpart.
Listing 4-14.
Reflectively getting and setting the values of instance and class fields
import java.lang.reflect.Field;
class X
{
public int i = 10;
public static final double PI = 3.14;
}
class FieldAccessDemo
{
public static void main(String[] args)
{
try
{
Class<?> clazz = Class.forName("X");
X x = (X) clazz.newInstance();
Field f = clazz.getField("i");