Discovering Class Fields


Class c = someObject.getClass(); Field[] publicFields = c.getFields(); for (int i = 0; i < publicFields.length; i++) {    String fieldName = publicFields[i].getName();    Class fieldType = publicFields[i].getType();    String fieldTypeStr = fieldType.getName();    System.out.println("Name: " + fieldName);    System.out.println("Type: " + fieldTypeStr); }



You can discover the public fields that belong to a class by using the getFields() method on a Class object. The getFields() method returns an array of Field objects containing one object per accessible public field. The accessible public fields returned do not all have to be fields contained directly within the class you are working with. The following fields are also returned:

  • Fields contained in a superclass

  • Fields contained in an implemented interface

  • Fields contained in an interface extended from an interface implemented by the class

Using the Field class, you can retrieve the field's name, type, and modifiers. In this phrase, we print out the name and type of each field. You can also get and set the value of a field. For more details on getting and setting the value of fields, see the phrases "Getting Field Values" and "Setting Field Values" also contained in this chapter.

You can also get an individual field instead of all the fields of an object if you know the field's name. The following example shows how you would get an individual field:

Class c = someObject.getClass(); Field titleField = c.getField("title");


In this example, we get a Field object representing the field with the name "title".

The getFields() and getField() methods return only the public data members. If you want to get all the fields of a class including private and protected fields, you can use the getdeclaredFields() or geTDeclaredField() methods. These methods behave like their getFields() and getField() counterparts except that they return all of the fields including private and protected fields.




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