Search code examples
javavariadic-functionstype-safety

Is @SafeVarargs an appropriate annotation for this method?


I have a bit of Java code (using the Guava ImmutableList class):

@Nonnull
public static <E extends Event> UserHistory<E> forUser(long id, E... events) {
    List<E> list = ImmutableList.copyOf(events);
    return new BasicUserHistory<E>(id, list);
}

I am getting the usual heap pollution warnings that come with a method like this. Since my method is not doing any modifications of events, it cannot introduce a heap pollution. However, if (because of erasure) a client of this method calls it with a bad events array, it seems that it can propagate a heap polution through itself.

If I annotate it with @SafeVarargs, I still get a warning in it (suppressable with @SuppressWarnings("varargs")). But reading the Java documentation on heap pollution, I am a little unclear as to the correct set of annotations on this method.

I also note that ImmutableList.copyOf is not marked as @SafeVarargs (though this could just be a compatibility issue), but Arrays.asList is.

So, my question: is @SafeVarargs an appropriate annotation for this method, given that it will not encounter a ClassCastException, but might propagate an improperly-checked array through to the final parameterized type and allow a ClastCastException in client code?

I believe, based on this answer, that it is safe, since the code does not do anything that depends on the type of events itself, only on the type of its elements. Is that a correct application of the guidance?


Solution

  • Yes, @SafeVarargs should be appropriate, because the only thing that is done with events is to pass it to ImmutableList.copyOf(), which (in my understanding of that method) does not depend on the runtime type of that array.

    ImmutableList.copyOf() should be annotated with @SafeVarargs, but it isn't (maybe for backwards compatibility or they haven't noticed it). When your non-reifiable varargs method passes the varargs parameter to another method that may potentially depend on the runtime type of the array, then (for reasons I don't fully understand, but is the subject of this question) it gives you a varargs warning for that call. This can be suppressed with @SuppressWarnings("varargs").