idea @NotNull 问题
时间: 2023-12-20 08:04:25 浏览: 317
在使用IDEA中的@NotNull注解时,它可以帮助我们在编码过程中检测方法的返回值、方法参数以及局部变量是否为空,从而减少空指针异常(NPE)的发生。原始的@NotNull注解和@Nullable注解最初只能使用JetBrains提供的一个Java注解的jar包下的注解。后来,IDEA提供了其他注解的替代方案。
要启用@NotNull注解的检测功能,需要在IDEA的配置中打开对应的选项。具体操作是:Preference(首选项)》Inspections(检查)》Java》Probable Bugs(可能的错误)》@NotNull/@Nullable Problems(非空/可空问题)。需要在左侧勾选@NotNull/@Nullable Problems,才能开启检测功能。
如果不想使用IDEA的注解,可以配置其他jar包的替代注解。在配置界面中,点击右下角的Configure annotations(配置注解),然后添加相应的替代注解,例如javax包的@Nonnull和@Nullable注解。
在编码过程中,@NotNull注解主要用于方法签名和方法调用。对于方法返回值,使用@Nullable注解表示如果方法的调用没有判空,会被提示警告。而使用@NotNull注解表示如果方法可能返回null,也会被提示警告。对于方法参数,使用@Nullable注解表示如果对参数直接使用没有判空,会被提示警告。而使用@NotNull注解表示如果调用时传入的参数可能为null,也会被提示警告。
此外,@NotNull注解也是JSR303(Bean的校验框架)的注解之一,在运行时检查一个属性是否为空,如果为空则视为不合法。它通常用于单独的变量上,表示该变量不能为空。一般配合@validation使用,当被@NotNull修饰的变量的值为空时,会抛出错误。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [【Java】idea @NotNull @Nullable 注解](https://blog.csdn.net/u010900754/article/details/91323427)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [@NotNull与@NonNull使用笔记](https://blog.csdn.net/tenerSainter/article/details/125022022)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文
相关推荐


















