Setting Field Values


String newTitle = "President"; Class c = someObject.getClass(); Field titleField = c.getField("title"); titleField.set(someObject, newTitle);



In order to set a field value, you must first get a Field object for the field you want to set the value of. See the phrase "Discovering Class Fields" in this chapter for more information about getting Field objects from a class. You should also refer to the phrase "Getting Field Values" also contained in this chapter for more information about getting field values.

The Field class has specialized methods for setting the values of primitive types. Methods such as setInt(), setFloat(), and setByte() allow you to set the values of the primitive types. For complete details of the set methods available on the Field object, see the JavaDoc at: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Field.html.

To set fields that are stored as objects rather than primitives, you use the more general set() method, passing the object instance for which you are setting field values and the value of the field as an object. In this phrase, we set the field named "title". After getting the field as a Field object, we then set the field's value using set(), passing the object instance we are setting field values on and the new value for the title string.

In this phrase, we knew the name of the field that we wanted to set the value for. We could set the value of a field even if we didn't know its name at compile time by combining this phrase with the "Discovering Class Fields" phrase presented earlier in this chapter. In that phrase, we show how to get field names. This technique could be useful in a tool such as a GUI builder, where you want to set the value of various GUI object fields, and the field names are not known until runtime.

Often, a debugger will let you change the value of a field during a debugging session. To implement a feature like that, the developer of the debugger would use this technique to set the fields value since the developer would not know which field's value you were setting at compile time.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net