Is @SafeVarargs an appropriate annotation for this method?

左心房为你撑大大i 提交于 2019-12-08 15:51:38

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/30130262/is-safevarargs-an-appropriate-annotation-for-this-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!