@SafeVarargs是否适合此方法?
我有一些Java代码(使用Guava ImmutableList
类):
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.
如果我用 @SafeVarargs
注释它,我仍会收到警告(可以用 @SuppressWarnings抑制) ( 可变参数)
)。但是阅读堆污染上的Java文档,我我对这个方法的正确注释集有点不清楚。
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.
我还注意到 ImmutableList.copyOf
是不标记为 @SafeVarargs
(虽然这可能只是兼容性问题),但 Arrays.asList
是。
I also note that ImmutableList.copyOf
is not marked as @SafeVarargs
(though this could just be a compatibility issue), but Arrays.asList
is.
所以,我的问题是: @SafeVarargs
这个方法的适当注释,给出它不会遇到 ClassCastException
,但可能会将未正确检查的数组传播到最终的参数化类型并允许 ClastCastException
在客户代码中?
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?
是的, @SafeVarargs
应该是合适的,因为用事件
完成的唯一事情就是将它传递给 ImmutableList.copyOf()
,(根据我对该方法的理解)不依赖于该数组的运行时类型。
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()
应 c> @SafeVarargs 注明,但
不是(可能是为了向后兼容,或者他们没有注意到了)。当你的不可恢复的varargs方法将varargs参数传递给另一个可能依赖于数组的运行时类型的方法时,(由于我不完全理解的原因,但是这个问题)它为你提供了一个varargs警告。这可以通过 @SuppressWarnings(varargs)
来抑制。
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")
.