【发布时间】:2013-10-02 13:57:53
【问题描述】:
我想使用@Nullable 注释来消除NullPointerExceptions。
在网上找了一些教程,注意到这个注解来自包javax.annotation.Nullable;
但是当我导入它时会产生编译错误:找不到符号
【问题讨论】:
标签: java annotations nullpointerexception nullable null-pointer
我想使用@Nullable 注释来消除NullPointerExceptions。
在网上找了一些教程,注意到这个注解来自包javax.annotation.Nullable;
但是当我导入它时会产生编译错误:找不到符号
【问题讨论】:
标签: java annotations nullpointerexception nullable null-pointer
你需要包含这个类所在的jar。你可以找到它here
如果使用Maven,可以添加如下依赖声明:
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
对于 Gradle:
dependencies {
testImplementation 'com.google.code.findbugs:jsr305:3.0.2'
}
【讨论】:
javax 包的类型?没有提供这种类型的带有javax-prefixed groupId 的工件吗?
com.google.code.findbugs 的groupId,因为它被托管在谷歌的代码托管解决方案上
工件已从 net.sourceforge.findbugs 移至
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.0</version>
</dependency>
【讨论】:
如果您使用的是 Gradle,则可以像这样包含依赖项:
repositories {
mavenCentral()
}
dependencies {
compile group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.0'
}
【讨论】:
'java'(或其他)插件已经创建了compile configuration。
<dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>jsr305</artifactId> <version>3.0.0</version> </dependency> Eclipse 报错: Missing artifact com.google.code.findbugs:jsr305:jar:3.0.0 Failure to transfer com.google.code.findbugs:jsr305:jar:3.0.0
compileOnly group...而不是compile group...
如果有人在尝试编译 Android 项目时遇到此问题,android.support.annotation.Nullable 中有一个替代的 Nullable 实现。因此,请注意您在 imports 中引用了哪个包。
【讨论】:
我正在使用包含注释的 Guava:
(分级代码)
compile 'com.google.guava:guava:23.4-jre'
【讨论】:
com.google.code.findbugs:jsr305 名字不好,不过是官方参考实现。
如果有人在外部构建在 IntelliJ IDEA 中创建的 Maven 项目时遇到此问题,我使用以下依赖项而不是答案:
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>15.0</version>
</dependency>
使用它可以让项目在 IntelliJ IDEA 上构建,并自行使用 Maven。
你可以找到它here。
【讨论】:
org.jetbrains:annotations:15.0 提供@org.jetbrains.annotations.Nullable 而不是@javax.annotation.Generated。如果您将某些代码生成器用作openapi-generator-maven-plugin,这可能是个问题。
对于 Android 项目,您可以通过如下更改项目/模块 gradle 文件 (build.gradle) 来修复此错误:
dependencies { implementation 'com.android.support:support-annotations:24.2.0' }
更多信息,请参考here。
【讨论】:
您可以通过在 gradle.build 中添加以下行来添加最新版本。
implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'
【讨论】:
JSR-305 是扩展规范的“Java 规范请求”。 @Nullable 等是其中的一部分;但是,从那时起(See this SO question),它似乎就处于“休眠”(或冻结)状态。所以要使用这些注解,你必须自己添加库。
FindBugs 已重命名为 SpotBugs,并且正在使用该名称进行开发。
对于 maven,这是 当前 annotation-only 依赖项(其他集成 here):
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<version>4.2.0</version>
</dependency>
如果您想使用完整的插件,请参阅 SpotBugs 的文档。
【讨论】: