首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NonNull局部变量

NonNull局部变量
EN

Stack Overflow用户
提问于 2020-01-23 18:18:52
回答 2查看 699关注 0票数 1

有办法在Java中为局部变量使用@NonNull吗?我使用的是带有@NonNullApi@NonNullFields注释的package-info.java,但在IDE中,对于局部变量的警告似乎与字段、方法和参数的警告不同。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-30 15:23:32

为了得到我想要的行为,我最终创建了一个注释,并删除了@NonNullFields@NonNullApi

下面是我使用的注释:

代码语言:javascript
复制
    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 {

    }
票数 1
EN

Stack Overflow用户

发布于 2020-01-30 03:21:14

不怎么有意思。你可以让你的变量final。这将导致不允许它成为null,但是这是一个编译时特性,而不是在运行时验证参数,因此它们是两个不同的概念。Kotlin有可空的概念,但是在Optional中只有真正的Optional,这是不一样的。

如果您想在运行时将请求参数验证添加到函数和或变量中,这是面向方面编程的一个典型示例,在Java中,您需要依赖某种特殊的魔法(如Spring )来完成这一任务(或AspectJ等),但是幕后将使用简单的设计模式,比如代理,或者任何其他方法。

注释只是一天结束时的元数据,依赖于其他适当地阅读和解释它们的东西,如果使用Spring注释,可能需要在Spring bean中的方法/字段上使用它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59884861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档