未注释的方法覆盖了使用@NotNull注释的方法

65

我正在实现一个自定义的数据结构,其中具有一些集合的属性和一些列表的属性。然而,对于大多数已实现的方法,在Java 7的IntelliJ IDEA上,会收到以下奇怪的警告:

未注释的方法覆盖了用@NotNull注释的方法

编辑:下面的代码与问题无关,只是原始问题的一部分。这个警告出现是因为IntelliJ中的一个bug。请参见答案(希望能)解决您的问题。


我找不到任何相关的信息,也不确定是否确实缺少某种检查,但我已经查看了ArrayList和List接口的源代码,却看不到这个警告实际上是关于什么的。它出现在每个引用列表字段的已实现方法上。以下是我编写的类的一部分代码:

public class ListHashSet<T> implements List<T>, Set<T> {
private ArrayList<T> list;
private HashSet<T> set;


/**
 * Constructs a new, empty list hash set with the specified initial
 * capacity and load factor.
 *
 * @param      initialCapacity the initial capacity of the list hash set
 * @param      loadFactor      the load factor of the list hash set
 * @throws     IllegalArgumentException  if the initial capacity is less
 *               than zero, or if the load factor is nonpositive
 */
public ListHashSet(int initialCapacity, float loadFactor) {
    set = new HashSet<>(initialCapacity, loadFactor);
    list = new ArrayList<>(initialCapacity);
}
...
/**
 * The Object array representation of this collection
 * @return an Object array in insertion order
 */
@Override
public Object[] toArray() {  // warning is on this line for the toArray() method
    return list.toArray();
}

编辑:我在这个类中有这些额外的构造函数:

public ListHashSet(int initialCapacity) {
    this(initialCapacity, .75f);
}

public ListHashSet() {
    this(16, .75f);
}

IntelliJ有自己的NotNull注解类。我想知道它是否在返回list.toArray时进行了一些手法,因为这是唯一可能出现NPE的地方。 - Totoro
列表字段不可能为空。除非我漏掉了什么? - BrDaHa
编译器添加了一个隐式的ListHashSet()构造函数。 - Totoro
1
我曾试图在IntelliJ论坛上询问,但没有得到任何答案。这很可能是IntelliJ中的一个错误。 - BrDaHa
这很奇怪,我仍然在五年后得到了这个问题的赞同。没有人修复吗? - BrDaHa
显示剩余2条评论
4个回答

91
尝试在toArray方法中添加@Nonnull (javax.annotation.Nonnull)。

当我添加了这个注释后,警告消失了。 我认为警告信息是不正确的,它说缺少@NotNull


2
哦,终于成功了!所以你的意思是说,“@NotNull is missing”这个警告信息实际上是一个错别字? - BrDaHa
2
对于那些不想在大类中的每个方法上都加注释的人,可以在包级别上添加@NonNullApi:https://dev59.com/1Goy5IYBdhLWcg3wq_sk#8405562 - teuber789

6
我同意Nonnull和NotNull之间存在打字错误。然而,还似乎存在其他一些bug。我正在实现一个自定义Set,它抱怨Iterator和toArray方法没有注释。但是,查看JDK,似乎在Set或Collection接口上没有这样的注释。

http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/0eb62e4a75e6/src/share/classes/java/util/Set.java http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/0eb62e4a75e6/src/share/classes/java/util/Collection.java

奇怪。

无论如何,另一种选择是在您的类或方法中添加@SuppressWarnings标签: @SuppressWarnings("NullableProblems")


如果我没记错的话,我们使用的是Oracle JDK,因此OpenJDK的实现可能会有所不同。 - BrDaHa
+1 表示正确地声明 @SuppressWarnings 指令,这似乎是唯一不依赖于依赖项的选项。 - Henry
4
我不同意“SuppressWarnings”是这里正确的方法。 - BrDaHa

1

我也遇到了同样的问题,并通过为该包添加package-info.java来解决它。在package-info.java下添加了注释@NonNullApi。 我的package-info.java看起来像这样 -

@NonNullApi
package org.example.auth.repositories;

import org.springframework.lang.NonNullApi;

0

尝试添加:

private ListHashSet() {}

我实际上有这些额外的构造函数(在原问题中更新)^ - BrDaHa
这不是问题的根源,但您认为您可能想在此处设置列表?private ArrayList<T> getList() { return list != null ? list : new ArrayList<T>(); } - Totoro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接