Java Reference
In-Depth Information
System.out.println(f.getInt(x)); // Output: 10
f.setInt(x, 20);
System.out.println(f.getInt(x)); // Output: 20
f = clazz.getField("PI");
System.out.println(f.getDouble(null)); // Output:
3.14
f.setDouble(x, 20);
System.out.println(f.getDouble(null)); // Never
executed
}
catch (Exception e)
{
System.err.println(e);
}
}
}
codewith
FieldAccessDemo
'ssourcecodeforconvenience.However,youcanima-
gine this source code being stored in a separate source file.
FieldAccessDemo
's
main()
methodfirstattemptstoload
X
,andthentriestoin-
stantiatethisclassvia
newInstance()
.Ifsuccessful,theinstanceisassignedtoref-
erence variable
x
.
main()
next invokes
Class
's
Field getField(String name)
method to
return a
Field
instance that represents the
public
field identified by
name
, which
happens to be
i
(in the first case) and
PI
(in the second case). This method throws
java.lang.NoSuchFieldException
when the named field doesn't exist.
Continuing,
main()
invokes
Field
's
getInt()
and
setInt()
methods (with
anobjectreference)togettheinstancefield'sinitialvalue,changethisvaluetoanother
value, and get the new value. The initial and new values are output.
Atthispoint,
main()
demonstratesclassfieldaccessinasimilarmanner.However,
itpasses
null
to
getInt()
and
setInt()
becauseanobjectreferenceisn'trequired
toaccessaclassfield.Because
PI
isdeclared
final
,thecallto
setInt()
resultsin
a thrown instance of the
IllegalAccessException
class.