eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)