在javax.annotation中找不到@Nullable.*

102 java annotations nullable nullpointerexception null-pointer

我想用@Nullable 注释来消除NullPointerExceptions.我在网上找到了一些教程,我注意到这个注释来自包javax.annotation.Nullable; 但是当我导入它时会产生编译错误:无法找到符号

dav*_*rld 126

您需要包含此类所在的jar.您可以在此处找到它

如果使用Maven,您可以添加以下依赖项声明:

<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>3.0.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

  • 为什么Google(特别是它的findbugs工件)提供属于`javax`包的类型?是不是有一个带有`javax`-prefixed groupId的工件提供这种类型? (63认同)
  • @AndrewSwan似乎作者选择了`com.google.code.findbugs`的groupId,因为它是托管在Google的代码托管解决方案上的 (8认同)
  • 仍然与 swagger 生成器相关 (7认同)
  • Google-findbugs 是 jsr305 的参考实现,因此我猜它们是允许使用 javax-packageName 的。 (3认同)

jan*_*jan 32

神器已经从移动net.sourceforge.findbugs

<dependency>
    <groupId>com.google.code.findbugs</groupId>
    <artifactId>jsr305</artifactId>
    <version>3.0.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)


mko*_*bit 26

如果您使用的是Gradle,则可以包含以下依赖项:

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
}
Run Code Online (Sandbox Code Playgroud)


Jan*_*eks 7

如果有人在尝试编译Android项目时有这个,那么有一个替代的Nullable实现android.support.annotation.Nullable.因此,请注意您在imports中引用的包.


Bot*_*War 7

JSR-305是扩展规范的“Java 规范请求”。@Nullable等是其中的一部分;但是从那以后它似乎是“休眠”(或冻结)(见这个问题)。所以要使用这些注解,你必须自己添加库。

FindBugs已重命名为SpotBugs,并且正在以该名称进行开发。

对于 maven,这是当前 仅注释的依赖项(此处的其他集成):

<dependency>
  <groupId>com.github.spotbugs</groupId>
  <artifactId>spotbugs-annotations</artifactId>
  <version>4.2.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

如果您想使用完整的插件,请参阅 SpotBugs 的文档。


小智 5

如果有人在外部构建在 IntelliJ IDEA 中创建的 Maven 项目时遇到此问题,我使用以下依赖项而不是答案:

<dependency>
  <groupId>org.jetbrains</groupId>
  <artifactId>annotations</artifactId>
  <version>15.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

使用这将允许项目在 IntelliJ IDEA 上构建,并使用 Maven 本身。

你可以在这里找到它。

  • 请注意,“org.jetbrains:annotations:15.0”提供“@org.jetbrains.annotations.Nullable”而不是“@javax.annotation.Generate”。如果您使用某些代码生成器作为“openapi-generator-maven-plugin”,这可能会出现问题。 (4认同)