简体   繁体   English

Java:抑制 NullPointerException 警告的方法注释

[英]Java: Method annotation to suppress NullPointerException warning

I have the following helper method in my code that asserts some property about a member field in my class.我的代码中有以下辅助方法,它断言有关我的 class 中成员字段的一些属性。

private @Nullable Controller mController;

private boolean isControllerReady() {
  return mController != null && mController.isReady();
}

Elsewhere in my code, I invoke something like this...在我的代码的其他地方,我调用了这样的东西......

if (isControllerReady() && mController.canDoSomething()) {
  mController.doSomething();
}

My Android Studio gives me a warning on canDoSomething() :我的 Android Studio 在canDoSomething()上给我一个警告:

Method invocation 'canDoSomething' may produce 'NullPointerException'

This should be a false positive.这应该是误报。 Is it possible to annotate isControllerReady so that the IDE suppresses/ignores this NPE warning on canDoSomething ?是否可以注释isControllerReady以便 IDE 抑制/忽略canDoSomething上的此 NPE 警告?

I think the @SuppressWarnings annotation is what you're looking for.我认为@SuppressWarnings注释正是您要找的。 Then you'd annotate your method and pass in the compiler warning (or warnings) that you'd like to suppress.然后你会注释你的方法并传入你想要抑制的编译器警告(或警告)。

@SuppressWarnings({"NullableProblems"})
private boolean isControllerReady() {
  return mController != null && mController.isReady();
}

Alternatively on Intellij (this should also work in Android Studio), you can press Alt + Enter on the highlighted warning and suppress it from there.或者在 Intellij 上(这应该也适用于 Android Studio),您可以在突出显示的警告上按Alt + Enter并从那里抑制它。

See https://www.jetbrains.com/help/idea/disabling-and-enabling-inspections.html?keymap=primary_xwin#suppress-inspections请参阅https://www.jetbrains.com/help/idea/disabling-and-enabling-inspections.html?keymap=primary_xwin#suppress-inspections

Edit: formatting编辑:格式化

As you annotated mController as a Nullable, the compiler tries to warn you to check if mController is not null before you invoke any operation on the object.当您将 mController 注释为 Nullable 时,编译器会尝试警告您在调用 object 上的任何操作之前检查 mController 是否不是 null。

You can simply add a null check in the condition.您可以简单地在条件中添加 null 检查。

if (isControllerReady() && mController != null && mController.canDoSomething()) {
  mController.doSomething();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM