Getting Field Values


Class c = anObject.getClass(); Field titleField = c.getField("title"); String titleVal = (String) titleField.get(anObject);



In order to get a field value, you must first get a Field object for the field you want to obtain the value of. See the phrase "Discovering Class Fields" earlier in this chapter for more information about getting Field objects from a class.

The Field class has specialized methods for getting the values of primitive types. Methods such as getInt(), getFloat(), and getByte() allow you to get the values of the primitive types. For complete details of the getter 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 get fields that are stored as objects rather than primitives, you use the more general get() method and cast the return result to the correct object type. In this phrase, we get the field named "title". After getting the field as a Field object, we then get the field's value using the get() method and casting the result as a String type.

In this phrase, we knew the name of the field that we wanted to get the value for. We could get 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. 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 get the value of various GUI object fields, and the field names are not known until runtime.




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