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:
f.setDouble(x, 20);
System.out.println(f.getDouble(null)); // Never
catch (Exception e)
Listing 4-14 declares classes X and FieldAccessDemo . I've included X 's source
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
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.
Search WWH ::

Custom Search