简体   繁体   中英

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.

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() :

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 ?

I think the @SuppressWarnings annotation is what you're looking for. 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.

See 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.

You can simply add a null check in the condition.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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