Java 中的 NotNull 在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42576760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:44:21  来源:igfitidea点击:

where is NotNull in java?

java

提问by user1244932

I want to compile simple code with oracle jdk 1.8:

我想用oracle jdk 1.8编译简单的代码:

class Foo {
   public static void test(@NotNull String a) {}
}

But ideanot understand such code, and suggest to add:

但是idea看不懂这样的代码,建议加上:

import com.sun.istack.internal.NotNull;

after that compilation inside ideaworks, but if run build by gradlewith such build.gradle:

在内部编译之后idea,但如果gradle使用这样的运行构建build.gradle

version '1.0-snaphshot_03.03.2017'

apply plugin: 'java'

targetCompatibility = '1.8'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

artifacts {
    archives sourcesJar
}

I got error:

我有错误:

error: package com.sun.istack.internal does not exist
import com.sun.istack.internal.NotNull;

 error: cannot find symbol
    public static void test(@NotNull String a) {
                                  ^
  symbol:   class NotNull
  location: class Foo

I thought that NotNullwas added in 1.8? How can I make possible of usage of NotNullin ideaand gradle?

我以为NotNull是加进去的1.8?我怎样才能使用NotNullinideagradle

回答by Kayaman

There is no @NotNullannotation in the standard JDK that would be meant for general use (the com.sun.internal.istack.NotNullis definitely not for your usage, as it's an internal class).

@NotNull标准 JDK 中没有用于一般用途的注释(com.sun.internal.istack.NotNull绝对不适合您使用,因为它是一个内部类)。

The Java Bean validation framework (JSR-303) has javax.validation.constraints.NotNull, which is implemented by (for example) Hibernate validator. That's probablywhat you're looking for.

Java Bean 验证框架 (JSR-303) 具有javax.validation.constraints.NotNull,由(例如)Hibernate 验证器实现。这可能就是你要找的。

回答by noobCoder

I think you should be adding org.jetbrains.annotations.NotNullas this is Used by IntelliJ IDEA IDE for static analysis. Refer :
IntelliJ Documentation
This SO Question

我认为您应该添加,org.jetbrains.annotations.NotNull因为 IntelliJ IDEA IDE 使用它进行静态分析。请参阅:
IntelliJ 文档
此 SO 问题