CodexBloom - Programming Q&A Platform

Java 17: NullPointerException when accessing nested optional properties with Lombok

πŸ‘€ Views: 4 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
java lombok optional nullpointerexception Java

I'm wondering if anyone has experience with I've spent hours debugging this and I'm encountering a `NullPointerException` when trying to access nested properties of an object that uses Lombok's `@Getter` and `@Setter` annotations in Java 17. I have a class structure where `User` has a `Profile`, and `Profile` has an `Address`. Here’s what my classes look like: ```java import lombok.Getter; import lombok.Setter; @Getter @Setter public class User { private Profile profile; } @Getter @Setter public class Profile { private Address address; } @Getter @Setter public class Address { private String street; } ``` When I try to access the street from the user's address like this: ```java User user = new User(); String street = user.getProfile().getAddress().getStreet(); ``` I get a `NullPointerException` on `user.getProfile()`. I expected that if `profile` is null, it should handle it gracefully. To debug this, I added null checks and printed intermediate states: ```java if (user.getProfile() != null) { if (user.getProfile().getAddress() != null) { System.out.println(user.getProfile().getAddress().getStreet()); } else { System.out.println("Address is null"); } } else { System.out.println("Profile is null"); } ``` However, I still want to access the street in a more concise way. I tried using `Optional` to avoid the `NullPointerException` like this: ```java String street = Optional.ofNullable(user) .map(User::getProfile) .map(Profile::getAddress) .map(Address::getStreet) .orElse("Default Street"); ``` But I still get a `NullPointerException` when `user` is null. Is there a better approach to handle this nested property access without cluttering my code with null checks? Am I missing something with using `Optional` here? Any guidance would be appreciated! I'm working on a service that needs to handle this. This is for a application running on CentOS.