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?