gpt4 book ai didi

java - 为什么@SafeVarargs 不抑制警告?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:04 24 4
gpt4 key购买 nike

代码如下:

class Foo<T> {
private final T[] array;
@SafeVarargs
Foo(T... items) {
this.array = items;
}
}

我得到:

[WARNING] Varargs method could cause heap pollution 
from non-reifiable varargs parameter items

我的作业有什么问题?如何解决? @SuppressWarnings 不是一个选项,因为我希望这个构造函数真正“安全”。

$ javac -version
javac 1.8.0_40

最佳答案

来自docs :

Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.

第一个语句告诉我们 @SafeVarargs 禁止未经检查的警告:

  • 可变参数的非具体化类型
  • 调用方法时创建参数化数组

在你的例子中,@SafeVarargs 抑制了对 T... items 的警告。您的警告发生在 this.array = items; 上。


来自JLS §9.6.4.7 :

The annotation @SafeVarargs has non-local effects because it suppresses unchecked warnings at method invocation expressions in addition to an unchecked warning pertaining to the declaration of the variable arity method itself.


In contrast, the annotation @SuppressWarnings("unchecked") has local effects because it only suppresses unchecked warnings pertaining to the declaration of a method.

关于java - 为什么@SafeVarargs 不抑制警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675503/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com