Search code examples
javalistspotbugsjava-record

How to solve EI_EXPOSE_REP in records for Lists


Spotbugs raises a warning EI_EXPOSE_REP (May expose internal representation by returning reference to mutable object) for the following code:

public record Example(
    List<String> ex) {

  public Example {
    ex =  List.copyOf(new ArrayList<>(ex));
  }
}

In FindBugs raises a bug called EI_EXPOSE_REP caused by Array something like that is proposed as a solution. But it does not seem to work anymore. Any hints how to resolve that? Is that a bug in Spotbugs? If there is no other way then to suppress it: Is it possible to suppress in on field level instead of on class level?

At the end I will need a solution which also works in a Null - Safe manner. For that I introduced an own copyOf method. Would be great if the solution at the ends work in that null safe manner. (But the Spotbugs warning appears independently if I use my own copyOf method, or the one in java.util.List)

public static <T> List<T> copyOf(List<T> listToCopy) {
    if (listToCopy == null) {
      return Collections.emptyList();
    }
    //noinspection Java9CollectionFactory: cannot be replaced as List.copyOf is not null safe.
    return Collections.unmodifiableList(new ArrayList<>(listToCopy));
}

Does not work with copyOf and also not with unmodifiableList.


Solution

  • Apart from making an immutable copy of the list in the constructor, you also need to update its getter.

    public List<String> ex() {
        return Collections.unmodifiableList(ex);
    }