Skip to content

Add ObjectUtils.nullSafeGetValue methods for null-safe value retrieval - #37509

Closed
lucky8987 wants to merge 16 commits into
spring-projects:mainfrom
lucky8987:main#null-safe
Closed

lucky8987 wants to merge 16 commits into
spring-projects:mainfrom
lucky8987:main#null-safe

Conversation

@lucky8987

Copy link
Copy Markdown
Contributor

ObjectUtils already provides a family of null-safe utilities such as
nullSafeEquals, nullSafeHashCode, and nullSafeToString. However, when
extracting a value from a potentially null object — for example, reading a
property from a header, attribute, or configuration value — there is currently
no equivalent convenience method, and callers have to write repetitive manual
null checks:

Object value = (obj != null ? obj.getName() : null);

or

  Object value = (obj != null && obj.getName() != null ? obj.getName() : "default");

Approach

This commit introduces two nullSafeGetValue methods to ObjectUtils:

  • nullSafeGetValue(T, Function<T, R>) — retrieves a value by applying the
    supplied get function to the given object, returning null if the given
    object is null.
  • nullSafeGetValue(T, Function<T, R>, R) — additionally accepts a default
    value which is returned if the given object is null or the supplied get
    function produced a null value.

Since the get function receives the object as its argument and is only invoked
when the object is non-null, the methods structurally guarantee that the
function is never applied to a null object — there is no risk of the
function dereferencing a captured null reference. This complements the
existing nullSafeEquals, nullSafeHashCode, and nullSafeToString family
of methods.

Looking forward to seeing this PR merged soon!

@bclozel

bclozel commented Oct 17, 2026

Copy link
Copy Markdown
Member

Thanks for the proposal but such utility classes are not meant to be broadly used by applications: their first goal must be to be used within the Framework. We didn't really miss this so far so I'm going to decline it.

@bclozel bclozel closed this Oct 17, 2026
@bclozel bclozel added the status: declined A suggestion or change that we don't feel we should currently apply label Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: declined A suggestion or change that we don't feel we should currently apply

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants