有办法在Java中为局部变量使用@NonNull吗?我使用的是带有@NonNullApi和@NonNullFields注释的package-info.java,但在IDE中,对于局部变量的警告似乎与字段、方法和参数的警告不同。
发布于 2020-01-30 15:23:32
为了得到我想要的行为,我最终创建了一个注释,并删除了@NonNullFields和@NonNullApi。
下面是我使用的注释:
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* This annotation can be applied to a package, class or method to indicate that the class fields,
* method return types and parameters in that element are not null by default unless there is:
* The method overrides a method in a superclass (in which
* case the annotation of the corresponding parameter in the superclass applies) there is a
* default parameter annotation applied to a more tightly nested element.
*/
@Documented
@Nonnull
@TypeQualifierDefault(
{
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.LOCAL_VARIABLE,
ElementType.METHOD,
ElementType.PACKAGE,
ElementType.PARAMETER,
ElementType.TYPE
})
@Retention(RetentionPolicy.RUNTIME)
public @interface NonNullByDefault {
}发布于 2020-01-30 03:21:14
不怎么有意思。你可以让你的变量final。这将导致不允许它成为null,但是这是一个编译时特性,而不是在运行时验证参数,因此它们是两个不同的概念。Kotlin有可空的概念,但是在Optional中只有真正的Optional,这是不一样的。
如果您想在运行时将请求参数验证添加到函数和或变量中,这是面向方面编程的一个典型示例,在Java中,您需要依赖某种特殊的魔法(如Spring )来完成这一任务(或AspectJ等),但是幕后将使用简单的设计模式,比如代理,或者任何其他方法。
注释只是一天结束时的元数据,依赖于其他适当地阅读和解释它们的东西,如果使用Spring注释,可能需要在Spring bean中的方法/字段上使用它。
https://stackoverflow.com/questions/59884861
复制相似问题