1. Overview
In this tutorial, we’ll inspect the runtime structure of a Java application using reflection. Specifically, we’ll use Java Reflection API*.* First, we inspect the fields of a Java class and then look at fields that the class inherits from a superclass.
2. Retrieving Fields from a Java Class
Let’s look at how to retrieve the fields of a class, regardless of their visibility.
Now, suppose we have a Person class with two fields that denote the lastName and firstName of a person:
public class Person {
protected String lastName;
private String firstName;
}
So, we have protected and private fields that won’t be explicitly visible to other classes. Nevertheless, we can use the Class::getDeclaredFields method to get all declared fields. The getDeclaredFields() method returns an array of Field objects alongside all the metadata of the fields:
List<Field> allFields = Arrays.asList(Person.class.getDeclaredFields());
assertEquals(2, allFields.size());
Field lastName = allFields.stream()
.filter(field -> field.getName().equals(LAST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, lastName.getType());
Field firstName = allFields.stream()
.filter(field -> field.getName().equals(FIRST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, firstName.getType());
To test the method, we simply filter the returned array by field names and check their types.
3. Retrieving Inherited Fields
Let’s now see how to get the inherited fields of a Java class.
Quickly, let’s extend the Person class with additional public fields and name it Employee:
public class Employee extends Person {
public static final String LABEL = "employee";
public int employeeId;
}
3.1. Retrieving Inherited Fields on a Simple Class Hierarchy
Similarly, calling getDeclaredFields() on the Employee class will return only the employeeId and LABEL fields. But we want the fields of the Person superclass. Of course, we could use the getDeclaredFields() method on both Person and Employee classes and merge their results into a single array. But what if we don’t want to specify the superclass explicitly? In this case, we can use the Java Reflection API method Class::getSuperclass().
The .getSuperClass() method returns the superclass of our class without referring explicitly to the name of the superclass. Now, we can get all the fields from the superclass and merge them into a single array:
List<Field> personFields = Arrays.asList(Employee.class.getSuperclass().getDeclaredFields());
List<Field> employeeFields = Arrays.asList(Employee.class.getDeclaredFields());
List<Field> allFields = Stream.concat(personFields.stream(), employeeFields.stream())
.collect(Collectors.toList());
assertEquals(4, allFields.size());
Field lastNameField = allFields.stream()
.filter(field -> field.getName().equals(LAST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, lastNameField.getType());
Field firstNameField = allFields.stream()
.filter(field -> field.getName().equals(FIRST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, firstNameField.getType());
Field employeeIdField = allFields.stream()
.filter(field -> field.getName().equals(EMPLOYEE_ID_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(employeeIdField.getType(), int.class);
Field employeeTypeField = allFields.stream()
.filter(field -> field.getName().equals(EMPLOYEE_TYPE_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, employeeTypeField.getType());
We can see here that we’ve gathered the two fields of Person and the two fields of Employee.
Reflection is a very powerful tool that should be used with caution. For example, we don’t advise using private fields of a class as we typically intend to hide them and prevent their usage. We should only use fields that can be inherited, such as public and protected fields.
3.2. Filtering public and protected Fields
Unfortunately, no method in the Java API allows us to get only the public and protected fields from a class and its superclasses. The Class::getFields() method approaches our goal by returning all public fields of a class and its superclasses, but not the protected ones. Therefore, we must use the .getDeclaredFields() method and filter its results using the getModifiers() method on the Field class.
The getModifiers() method returns an int representing the field’s modifiers. This value is an integer between 2^0 and 2^7. In particular, public is 2^0, and static is 2^3. Therefore, calling the getModifiers() method on a public and static field would return 9.
We can ignore the implementation details and directly use the helper methods provided by the Modifiers class. In particular, we’ll use the .isPublic() and the .isProtected() methods to gather only the public and protected fields, respectively:
List<Field> personFields = Arrays.stream(Employee.class.getSuperclass().getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
assertEquals(1, personFields.size());
Field personField = personFields.stream()
.filter(field -> field.getName().equals(LAST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found"));
assertEquals(String.class, personField.getType());
In our test, we filtered out all the fields except the public and protected ones. We’re free to combine the modifiers’ methods to get specific fields. For example, to get only the public static final fields of an Employee class, we must filter for those specific modifiers:
List<Field> publicStaticField = Arrays.stream(Employee.class.getDeclaredFields())
.filter(field -> Modifier.isStatic(field.getModifiers()) && Modifier.isPublic(field.getModifiers()) &&
Modifier.isFinal(field.getModifiers()))
.collect(Collectors.toList());
assertEquals(1, publicStaticField.size());
Field employeeTypeField = publicStaticField.get(0);
assertEquals(EMPLOYEE_TYPE_FIELD, employeeTypeField.getName());
3.3. Retrieving Inherited Fields on a Deep Class Hierarchy
Until now, we have worked on a single-class hierarchy. What do we do if we have a deeper class hierarchy and want to gather all the inherited fields?
For example, if we have a subclass of Employee or a superclass of Person, obtaining the whole hierarchy’s fields will also require checking the superclasses’ superclass.
For this purpose, we can create a utility method that runs through the hierarchy, building the complete result for us:
List<Field> getAllFields(Class clazz) {
if (clazz == null) {
return Collections.emptyList();
}
List<Field> result = new ArrayList<>(getAllFields(clazz.getSuperclass()));
List<Field> filteredFields = Arrays.stream(clazz.getDeclaredFields())
.filter(f -> Modifier.isPublic(f.getModifiers()) || Modifier.isProtected(f.getModifiers()))
.collect(Collectors.toList());
result.addAll(filteredFields);
return result;
}
This recursive method will search public and protected fields through the class hierarchy and return all found in a List.
Let’s illustrate it with a little test on a new MonthEmployee class, extending the Employee class from our earlier example:
public class MonthEmployee extends Employee {
protected double reward;
}
This class defines a new field – reward. Given all the hierarchy classes, our method should give us three field definitions — Person::lastName, Employee::employeeId, and MonthEmployee::reward.
Let’s call the getAllFields() method on MonthEmployee:
List<Field> allFields = getAllFields(MonthEmployee.class);
assertEquals(4, allFields.size());
assertFalse(allFields.stream().anyMatch(field -> field.getName().equals(FIRST_NAME_FIELD)));
assertEquals(String.class, allFields.stream().filter(field -> field.getName().equals(LAST_NAME_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found")).getType());
assertEquals(int.class, allFields.stream().filter(field -> field.getName().equals(EMPLOYEE_ID_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found")).getType());
assertEquals(double.class, allFields.stream().filter(field -> field.getName().equals(MONTH_EMPLOYEE_REWARD_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found")).getType());
assertEquals(String.class, allFields.stream().filter(field -> field.getName().equals(EMPLOYEE_TYPE_FIELD))
.findFirst().orElseThrow(() -> new RuntimeException("Field not found")).getType());
As expected, we gathered all the public and protected fields from the class hierarchy.
4. Conclusion
In this article, we saw how to retrieve the fields of a Java class using the Java Reflection API.
We first learned how to retrieve the declared fields of a class. After that, we saw how to retrieve its superclass fields as well. Then, we learned to filter out non-public and non-protected fields.
Finally, we saw how to apply all this to gather the inherited fields of a multiple-class hierarchy.
As usual, the complete code for this article is available over on our GitHub.