javaguava

Cannot resolve symbol 'MoreObjects'


I have this old legacy code:

dependency com.google.guava:guava:15.0

@Entity
@Table(name = "profiles")
public class Profile {
    @Id
    @Column(name = "id", nullable = false)
    private UUID id;
    @JoinColumn(
    name = "recipient_profile")
    private Profile recipientProfile;
    ....
}

@Entity
@Table(name = "standalone_credit")
public class StandaloneCredit {
    @Id
    @Column(name = "id", nullable = false)
    private UUID id;
    @JoinColumn(name = "recipient_profile_internal_id")
    private Profile recipientBusinessProfile;
    ....
}

import com.google.common.base.MoreObjects;
StandaloneCredit credit;

Profile recipientProfile =
        MoreObjects.firstNonNull(credit.getRecipientProfile(), credit.getRecipientBusinessProfile());

com.google.guava:guava:15.0 is a dependency from implementation 'org.springframework.cloud:spring-cloud-starter-netflix-hystrix:2.2.10.RELEASE' How I can replace MoreObjects without breaking the code logic with core Java code implementation?


Solution

  • MoreObjects.firstNonNull can be directly replaced by Objects.requireNonNullElse:

    Profile recipientProfile = Objects.requireNonNullElse(
            credit.getRecipientProfile(), credit.getRecipientBusinessProfile());
    

    Recent versions of the Guava Javadocs have specific instructions to make this replacement, in fact:

    Java 9 users: use java.util.Objects.requireNonNullElse(first, second) instead.

    To add a little more context, the Guava MoreObjects.firstNonNull method predates Java 9 when Objects.requireNonNullElse was added to Java. The expectation is that users using Guava on newer versions of Java should migrate to the built-in Java method.

    Javadocs

    Reviewing the Javadocs of the two methods shows that they are expected to behave identically to each other.

    MoreObjects.firstNonNull

    public static <T> T firstNonNull​(@CheckForNull T first, @CheckForNull T second)

    Returns the first of two given parameters that is not null, if either is, or otherwise throws a NullPointerException.

    […]

    Throws:
    NullPointerException - if both first and second are null

    Objects.requireNonNullElse

    public static <T> T requireNonNullElse(T obj, T defaultObj)

    Returns the first argument if it is non-null and otherwise the second argument if it is non-null.

    […]

    Throws:
    NullPointerException - if both obj is null and defaultObj is null