How do I list the public fields of a class?
Author: Deron Eriksson
Description: This Java tutorial describes how to use the Class object's getMethods() method.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


If you have a Class object, you can obtain its public fields (including inherited fields) by calling getFields() on the Class object. This is demonstrated below using the ClassFieldTest class. It creates a FieldTest object. FieldTest extends the ParentFieldTest object. FieldTest has a public field, a protected field, and a private field, and ParentFieldTest also has a public field, a protected field, and a private field. We get the FieldTest object's Class object and call getFields on the class object. We then iterate over the fields and display them. The results are displayed down below our JavaSW classes.

ClassFieldTest.java

package test;

import java.lang.reflect.Field;

public class ClassFieldTest {

	public static void main(String args[]) {
		FieldTest ft = new FieldTest();
		Class ftClass = ft.getClass();

		Field[] fields = ftClass.getFields();
		for (int i = 0; i < fields.length; i++) {
			System.out.println("field: " + fields[i]);
		}
	}
}

Here is the ParentFieldTest class.

ParentFieldTest.java

package test;

public class ParentFieldTest {

	private String parentPri;
	protected String parentPro;
	public String parentPub;

	public ParentFieldTest() {
	}

}

Here is the FieldTest class.

FieldTest.java

package test;

public class FieldTest extends ParentFieldTest {

	private String pri;
	protected String pro;
	public String pub;

	public FieldTest() {
	}

	public FieldTest(String pri, String pro, String pub) {
		this.pri = pri;
		this.pro = pro;
		this.pub = pub;
	}

}

If we execute the ClassFieldTest class, we see the following results.

field: public java.lang.String test.FieldTest.pub
field: public java.lang.String test.ParentFieldTest.parentPub

As you can see, calling getFields() on a Class object returns the public fields of a class, including public fields that the class inherits from superclasses.