java safevarargs,@SafeVarargs是否适合此方法?

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

@Nonnull

public static UserHistory forUser(long id, E... events) {

List list = ImmutableList.copyOf(events);

return new BasicUserHistory(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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值