xenoterracide
xenoterracide

Reputation: 16865

How can I use SpEL to evaluate a subobject property where the subobject might be null

I want to evaluate

"user.name"

but user might be null, which of course results in an NPE is there a way to say only try to get name if user is not null? otherwise return null.

I read about the Elvis syntax, but I'm not sure how to apply it here

Upvotes: 0

Views: 55

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34806

You can use the safe navigation operator like this:

user?.name

This has the exact same behavior you describe - if the user is null, the expression will be evaluated to null, otherwise it will be evaluated to the value of user.name.

Upvotes: 2

Related Questions