Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 471
Michael Ekstrand Avatar asked May 08 '15 18:05

Michael Ekstrand


People also ask

What is @SafeVarargs annotation in Java?

It is an annotation which applies on a method or constructor that takes varargs parameters. It is used to ensure that the method does not perform unsafe operations on its varargs parameters. It was included in Java7 and can only be applied on. Final methods.

What is the use of SafeVarargs in Java?

Annotation Type SafeVarargsA programmer assertion that the body of the annotated method or constructor does not perform potentially unsafe operations on its varargs parameter.


1 Answers

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").

like image 52
newacct Avatar answered Oct 13 '22 01:10

newacct