getFields
- Java course
- Advanced
- Lesson 26/82
- 5 min
Learn field listing with getFields.
Finding fields with getFields
Class.getFields() returns all public fields of a class, including those inherited from superclasses. Each field is represented by a Field object.
Example: Field[] fields = Person.class.getFields(). In the returned array, for each element f.getName() gives the field name and f.getType() gives its type. To get only the class's own fields, use getDeclaredFields; this includes private ones too.
Reading field values
To read the value of a Field object you use get(obj). obj is the instance that holds the field; for static fields you pass null.
Example: Object value = f.get(person). This returns the value of field f on the person instance. To access private fields you must call f.setAccessible(true); otherwise an IllegalAccessException is thrown. This is a common way for libraries to inspect hidden fields in tests.
Practice Count the public fields of Person
Define a Person class with public String name and public int age fields. Get the fields into a Field[] with Person.class.getFields() and print the length with System.out.println.
Starter code
import java.lang.reflect.Field;
// Define the Person class (public name and age)
// Get the fields of Person.class with getFields
// Print the lengthSample solution
import java.lang.reflect.Field;
class Person {
public String name;
public int age;
}
public class PersonFields {
public static void main(String[] args) {
Field[] fields = Person.class.getFields();
System.out.println(fields.length);
}
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Field methods
| Term | Meaning |
|---|---|
getFields |
Public fields |
getDeclaredFields |
All declared |
getName |
Field name |
getType |
Field type |
2 Which method returns only public fields, including inherited ones?
- getDeclaredFields
- getFields Correct answer
- getMethods
- getClasses
Explanation: getFields returns public ones, including inherited.
3 Complete the getFields call
Field[] fields = clazz.____();
Field[] fields = clazz.getFields();
Explanation: getFields returns public fields.